Overview

Using Controllers

Actions are methods on a controller that handle requests. By default all public methods on a controller map to actions and are accessible by a URL. Actions are responsible for interpreting the request and creating the response. Usually responses are in the form of a rendered view, but there are other ways to create responses as well.

For instance, when you access a URL like this: http://localhost/blog/posts/show/2015/the-post-title Phalcon by default will decompose each part like this:

DescriptionSlug
Phalcon Directoryblog
Controllerposts
Actionshow
Parameter2015
Parameterthe-post-title

In this case, the PostsController will handle this request. There is no a special location to put controllers in an application, they could be loaded using Phalcon\Loader, so you’re free to organize your controllers as you need.

Controllers must have the suffix Controller while actions the suffix Action. A sample of a controller is as follows:

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class PostsController extends Controller
  4. {
  5. public function indexAction()
  6. {
  7. }
  8. public function showAction($year, $postTitle)
  9. {
  10. }
  11. }

Additional URI parameters are defined as action parameters, so that they can be easily accessed using local variables. A controller can optionally extend Phalcon\Mvc\Controller. By doing this, the controller can have easy access tothe application services.

Parameters without a default value are handled as required. Setting optional values for parameters is done as usual in PHP:

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class PostsController extends Controller
  4. {
  5. public function indexAction()
  6. {
  7. }
  8. public function showAction($year = 2015, $postTitle = 'some default title')
  9. {
  10. }
  11. }

Parameters are assigned in the same order as they were passed in the route. You can get an arbitrary parameter from its name in the following way:

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class PostsController extends Controller
  4. {
  5. public function indexAction()
  6. {
  7. }
  8. public function showAction()
  9. {
  10. $year = $this->dispatcher->getParam('year');
  11. $postTitle = $this->dispatcher->getParam('postTitle');
  12. }
  13. }

Dispatch Loop

The dispatch loop will be executed within the Dispatcher until there are no actions left to be executed. In the previous example only one action was executed. Now we’ll see how the forward() method can provide a more complex flow of operation in the dispatch loop, by forwarding execution to a different controller/action.

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class PostsController extends Controller
  4. {
  5. public function indexAction()
  6. {
  7. }
  8. public function showAction($year, $postTitle)
  9. {
  10. $this->flash->error(
  11. "You don't have permission to access this area"
  12. );
  13. // Forward flow to another action
  14. $this->dispatcher->forward(
  15. [
  16. 'controller' => 'users',
  17. 'action' => 'signin',
  18. ]
  19. );
  20. }
  21. }

If users don’t have permission to access a certain action then they will be forwarded to the signin action in the UsersController.

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class UsersController extends Controller
  4. {
  5. public function indexAction()
  6. {
  7. }
  8. public function signinAction()
  9. {
  10. }
  11. }

There is no limit on the forwards you can have in your application, so long as they do not result in circular references, at which point your application will halt. If there are no other actions to be dispatched by the dispatch loop, the dispatcher will automatically invoke the view layer of the MVC that is managed by Phalcon\Mvc\View.

Initializing Controllers

Phalcon\Mvc\Controller offers the initialize() method, which is executed first, before any action is executed on a controller. The use of the __construct() method is not recommended.

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class PostsController extends Controller
  4. {
  5. public $settings;
  6. public function initialize()
  7. {
  8. $this->settings = [
  9. 'mySetting' => 'value',
  10. ];
  11. }
  12. public function saveAction()
  13. {
  14. if ($this->settings['mySetting'] === 'value') {
  15. // ...
  16. }
  17. }
  18. }
The initialize() method is only called if the beforeExecuteRoute event is executed with success. This avoid that application logic in the initializer cannot be executed without authorization.

If you want to execute some initialization logic just after the controller object is constructed then you can implement the onConstruct() method:

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class PostsController extends Controller
  4. {
  5. public function onConstruct()
  6. {
  7. // ...
  8. }
  9. }
Be aware that onConstruct() method is executed even if the action to be executed doesn’t exist in the controller or the user does not have access to it (according to custom control access provided by the developer).

Injecting Services

If a controller extends Phalcon\Mvc\Controller then it has easy access to the service container in application. For example, if we have registered a service like this:

  1. <?php
  2. use Phalcon\Di;
  3. $di = new Di();
  4. $di->set(
  5. 'storage',
  6. function () {
  7. return new Storage(
  8. '/some/directory'
  9. );
  10. },
  11. true
  12. );

Then, we can access that service in several ways:

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class FilesController extends Controller
  4. {
  5. public function saveAction()
  6. {
  7. // Injecting the service by just accessing the property with the same name
  8. $this->storage->save('/some/file');
  9. // Accessing the service from the DI
  10. $this->di->get('storage')->save('/some/file');
  11. // Another way to access the service using the magic getter
  12. $this->di->getStorage()->save('/some/file');
  13. // Another way to access the service using the magic getter
  14. $this->getDi()->getStorage()->save('/some/file');
  15. // Using the array-syntax
  16. $this->di['storage']->save('/some/file');
  17. }
  18. }

If you’re using Phalcon as a full-stack framework, you can read the services provided by default in the framework.

Request and Response

Assuming that the framework provides a set of pre-registered services. We explain how to interact with the HTTP environment. The request service contains an instance of Phalcon\Http\Request and the response contains a Phalcon\Http\Response representing what is going to be sent back to the client.

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class PostsController extends Controller
  4. {
  5. public function indexAction()
  6. {
  7. }
  8. public function saveAction()
  9. {
  10. // Check if request has made with POST
  11. if ($this->request->isPost()) {
  12. // Access POST data
  13. $customerName = $this->request->getPost('name');
  14. $customerBorn = $this->request->getPost('born');
  15. }
  16. }
  17. }

The response object is not usually used directly, but is built up before the execution of the action, sometimes - like in an afterDispatch event - it can be useful to access the response directly:

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class PostsController extends Controller
  4. {
  5. public function indexAction()
  6. {
  7. }
  8. public function notFoundAction()
  9. {
  10. // Send a HTTP 404 response header
  11. $this->response->setStatusCode(404, 'Not Found');
  12. }
  13. }

Learn more about the HTTP environment in their dedicated articles request and response.

Session Data

Sessions help us maintain persistent data between requests. You can access a Phalcon\Session\Bag from any controller to encapsulate data that needs to be persistent:

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class UserController extends Controller
  4. {
  5. public function indexAction()
  6. {
  7. $this->persistent->name = 'Michael';
  8. }
  9. public function welcomeAction()
  10. {
  11. echo 'Welcome, ', $this->persistent->name;
  12. }
  13. }

Using Services as Controllers

Services may act as controllers, controllers classes are always requested from the services container. Accordingly, any other class registered with its name can easily replace a controller:

  1. <?php
  2. // Register a controller as a service
  3. $di->set(
  4. 'IndexController',
  5. function () {
  6. $component = new Component();
  7. return $component;
  8. }
  9. );
  10. // Register a namespaced controller as a service
  11. $di->set(
  12. 'Backend\Controllers\IndexController',
  13. function () {
  14. $component = new Component();
  15. return $component;
  16. }
  17. );

Events in Controllers

Controllers automatically act as listeners for dispatcher events, implementing methods with those event names allow you to implement hook points before/after the actions are executed:

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class PostsController extends Controller
  4. {
  5. public function beforeExecuteRoute($dispatcher)
  6. {
  7. // This is executed before every found action
  8. if ($dispatcher->getActionName() === 'save') {
  9. $this->flash->error(
  10. "You don't have permission to save posts"
  11. );
  12. $this->dispatcher->forward(
  13. [
  14. 'controller' => 'home',
  15. 'action' => 'index',
  16. ]
  17. );
  18. return false;
  19. }
  20. }
  21. public function afterExecuteRoute($dispatcher)
  22. {
  23. // Executed after every found action
  24. }
  25. }