How to create a new controller in Phalcon?

Member

by ryleigh , in category: PHP Frameworks , a year ago

How to create a new controller in Phalcon?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by aubrey , a year ago

@ryleigh 

To create a new controller in Phalcon, follow these steps:

  1. Create a new file in the app/controllers directory with a name that ends with "Controller.php". For example, if you want to create a controller for handling user-related actions, you might create a file called UserController.php.
  2. In this new file, define a class with the same name as the file, but without the "Controller" suffix. For example, if your file is called UserController.php, the class should be called User.
  3. Extend the PhalconMvcController class, which provides the basic functionality of a Phalcon controller. For example, your class declaration should look like this:
1
2
3
4
class User extends PhalconMvcController
{
    // ...
}


  1. Define one or more action methods in your controller. These methods will handle requests for specific URLs. For example, to handle a request to /user/login, you might define a method called loginAction():
1
2
3
4
public function loginAction()
{
    // Handle login request
}


  1. (Optional) Define any helper methods or properties that your controller needs. For example, you might define a $userModel property that contains an instance of your user model.


That's it! Your new controller is now ready to use. To use it in your application, you'll need to define a route that maps a URL to one of your controller's action methods. You can do this in the app/config/routes.php file, using the add() method of the $router object. For example:

1
2
3
4
$router->add('/user/login', [
    'controller' => 'User',
    'action' => 'login'
]);


This will map requests to /user/login to the loginAction() method of your User controller.