Tutorial - INVO


Invo - 图1

INVO

In this tutorial, we’ll explain a more complete application in order to gain a deeper understanding of developing with Phalcon. INVO is one of the sample applications we have created. INVO is a small website that allows users to generate invoices and do other tasks such as manage customers and products. You can clone its code from GitHub.

INVO was made with the client-side framework Bootstrap. Although the application does not generate actual invoices, it still serves as an example showing how the framework works.

Project Structure

Once you clone the project in your document root you’ll see the following structure:

  1. invo/
  2. app/
  3. config/
  4. controllers/
  5. forms/
  6. library/
  7. logs/
  8. models/
  9. plugins/
  10. views/
  11. cache/
  12. volt/
  13. docs/
  14. public/
  15. css/
  16. fonts/
  17. js/
  18. schemas/

As you know, Phalcon does not impose a particular file structure for application development. This project has a simple MVC structure and a public document root.

Once you open the application in your browser https://localhost/invo you’ll see something like this:

Invo - 图2

The application is divided into two parts: a frontend and a backend. The frontend is a public area where visitors can receive information about INVO and request contact information. The backend is an administrative area where registered users can manage their products and customers.

Routing

INVO uses the standard route that is built-in with the Router component. These routes match the following pattern: /:controller/:action/:params. This means that the first part of a URI is the controller, the second the controller action and the rest are the parameters.

The following route /session/register executes the controller SessionController and its action registerAction.

Configuration

INVO has a configuration file that sets general parameters in the application. This file is located at app/config/config.ini and is loaded in the very first lines of the application bootstrap (public/index.php):

  1. <?php
  2. use Phalcon\Config\Adapter\Ini as ConfigIni;
  3. // ...
  4. // Read the configuration
  5. $config = new ConfigIni(
  6. APP_PATH . 'app/config/config.ini'
  7. );

Phalcon Config (Phalcon\Config) allows us to manipulate the file in an object-oriented way. In this example, we’re using an ini file for configuration but Phalcon has adapters for other file types as well. The configuration file contains the following settings:

  1. [database]
  2. host = localhost
  3. username = root
  4. password = secret
  5. name = invo
  6. [application]
  7. controllersDir = app/controllers/
  8. modelsDir = app/models/
  9. viewsDir = app/views/
  10. pluginsDir = app/plugins/
  11. formsDir = app/forms/
  12. libraryDir = app/library/
  13. baseUri = /invo/

Phalcon doesn’t have any pre-defined settings convention. Sections help us to organize the options as appropriate. In this file there are two sections to be used later: application and database.

Autoloaders

The second part that appears in the bootstrap file (public/index.php) is the autoloader:

  1. <?php
  2. /**
  3. * Auto-loader configuration
  4. */
  5. require APP_PATH . 'app/config/loader.php';

The autoloader registers a set of directories in which the application will look for the classes that it will eventually need.

  1. <?php
  2. $loader = new Phalcon\Loader();
  3. // We're a registering a set of directories taken from the configuration file
  4. $loader->registerDirs(
  5. [
  6. APP_PATH . $config->application->controllersDir,
  7. APP_PATH . $config->application->pluginsDir,
  8. APP_PATH . $config->application->libraryDir,
  9. APP_PATH . $config->application->modelsDir,
  10. APP_PATH . $config->application->formsDir,
  11. ]
  12. );
  13. $loader->register();

Note that the above code has registered the directories that were defined in the configuration file. The only directory that is not registered is the viewsDir because it contains HTML + PHP files but no classes. Also, note that we use a constant called APP_PATH. This constant is defined in the bootstrap (public/index.php) to allow us to have a reference to the root of our project:

  1. <?php
  2. // ...
  3. define(
  4. 'APP_PATH',
  5. realpath('..') . '/'
  6. );

Registering services

Another file that is required in the bootstrap is (app/config/services.php). This file allows us to organize the services that INVO uses.

  1. <?php
  2. /**
  3. * Load application services
  4. */
  5. require APP_PATH . 'app/config/services.php';

Service registration is achieved with closures for lazy loading the required components:

  1. <?php
  2. use Phalcon\Url as UrlProvider;
  3. // ...
  4. /**
  5. * The URL component is used to generate all kind of URLs in the application
  6. */
  7. $di->set(
  8. 'url',
  9. function () use ($config) {
  10. $url = new UrlProvider();
  11. $url->setBaseUri(
  12. $config->application->baseUri
  13. );
  14. return $url;
  15. }
  16. );

We will discuss this file in depth later.

Handling the Request

If we skip to the end of the file (public/index.php), the request is finally handled by Phalcon\Mvc\Application which initializes and executes all that is necessary to make the application run:

  1. <?php
  2. use Phalcon\Mvc\Application;
  3. // ...
  4. $application = new Application($di);
  5. $response = $application->handle(
  6. $_SERVER["REQUEST_URI"]
  7. );
  8. $response->send();

Dependency Injection

In the first line of the code block above, the Application class constructor is receiving the variable $di as an argument. What is the purpose of that variable? Phalcon is a highly decoupled framework so we need a component that acts as glue to make everything work together. That component is Phalcon\Di. It’s a service container that also performs dependency injection and service location, instantiating all components as they are needed by the application.

There are many ways of registering services in the container. In INVO, most services have been registered using anonymous functions/closures. Thanks to this, the objects are instantiated in a lazy way, reducing the resources needed by the application.

For instance, in the following excerpt the session service is registered. The anonymous function will only be called when the application requires access to the session data:

  1. <?php
  2. use Phalcon\Session\Adapter\Files as Session;
  3. // ...
  4. // Start the session the first time a component requests the session service
  5. $di->set(
  6. 'session',
  7. function () {
  8. $session = new Session();
  9. $session->start();
  10. return $session;
  11. }
  12. );

Here, we have the freedom to change the adapter, perform additional initialization and much more. Note that the service was registered using the name session. This is a convention that will allow the framework to identify the active service in the services container.

A request can use many services and registering each service individually can be a cumbersome task. For that reason, the framework provides a variant of Phalcon\Di called Phalcon\Di\FactoryDefault whose task is to register all services providing a full-stack framework.

  1. <?php
  2. use Phalcon\Di\FactoryDefault;
  3. // ...
  4. // The FactoryDefault Dependency Injector automatically registers the
  5. // right services providing a full-stack framework
  6. $di = new FactoryDefault();

It registers the majority of services with components provided by the framework as standard. If we need to override the definition of some service we could just set it again as we did above with session or url. This is the reason for the existence of the variable $di.

Log into the Application

A log in facility will allow us to work on backend controllers. The separation between backend controllers and frontend ones is only logical. All controllers are located in the same directory (app/controllers/).

To enter the system, users must have a valid username and password. Users are stored in the table users in the database invo.

Before we can start a session, we need to configure the connection to the database in the application. A service called db is set up in the service container with the connection information. As with the autoloader, we are again taking parameters from the configuration file in order to configure a service:

  1. <?php
  2. use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
  3. // ...
  4. // Database connection is created based on parameters defined in the configuration file
  5. $di->set(
  6. 'db',
  7. function () use ($config) {
  8. return new DbAdapter(
  9. [
  10. 'host' => $config->database->host,
  11. 'username' => $config->database->username,
  12. 'password' => $config->database->password,
  13. 'dbname' => $config->database->name,
  14. ]
  15. );
  16. }
  17. );

Here, we return an instance of the MySQL connection adapter. If needed, you could do extra actions such as adding a logger, a profiler or change the adapter, setting it up as you want.

The following simple form (app/views/session/index.volt) requests the login information. We’ve removed some HTML code to make the example more concise:

  1. {{ form('session/start') }}
  2. <fieldset>
  3. <div>
  4. <label for='email'>
  5. Username/Email
  6. </label>
  7. <div>
  8. {{ text_field('email') }}
  9. </div>
  10. </div>
  11. <div>
  12. <label for='password'>
  13. Password
  14. </label>
  15. <div>
  16. {{ password_field('password') }}
  17. </div>
  18. </div>
  19. <div>
  20. {{ submit_button('Login') }}
  21. </div>
  22. </fieldset>
  23. {{ endForm() }}

Instead of using raw PHP as the previous tutorial, we started to use Volt. This is a built-in template engine inspired by Jinja_ providing a simpler and friendly syntax to create templates. It will not take too long before you become familiar with Volt.

The SessionController::startAction function (app/controllers/SessionController.php) has the task of validating the data entered in the form including checking for a valid user in the database:

  1. <?php
  2. class SessionController extends ControllerBase
  3. {
  4. // ...
  5. private function _registerSession($user)
  6. {
  7. $this->session->set(
  8. 'auth',
  9. [
  10. 'id' => $user->id,
  11. 'name' => $user->name,
  12. ]
  13. );
  14. }
  15. /**
  16. * This action authenticate and logs a user into the application
  17. */
  18. public function startAction()
  19. {
  20. if ($this->request->isPost()) {
  21. // Get the data from the user
  22. $email = $this->request->getPost('email');
  23. $password = $this->request->getPost('password');
  24. // Find the user in the database
  25. $user = Users::findFirst(
  26. [
  27. "(email = :email: OR username = :email:) AND password = :password: AND active = 'Y'",
  28. 'bind' => [
  29. 'email' => $email,
  30. 'password' => sha1($password),
  31. ]
  32. ]
  33. );
  34. if ($user !== false) {
  35. $this->_registerSession($user);
  36. $this->flash->success(
  37. 'Welcome ' . $user->name
  38. );
  39. // Forward to the 'invoices' controller if the user is valid
  40. return $this->dispatcher->forward(
  41. [
  42. 'controller' => 'invoices',
  43. 'action' => 'index',
  44. ]
  45. );
  46. }
  47. $this->flash->error(
  48. 'Wrong email/password'
  49. );
  50. }
  51. // Forward to the login form again
  52. return $this->dispatcher->forward(
  53. [
  54. 'controller' => 'session',
  55. 'action' => 'index',
  56. ]
  57. );
  58. }
  59. }

For the sake of simplicity, we have used sha1 to store the password hashes in the database, however, this algorithm is not recommended in real applications, use bcrypt instead.

Note that multiple public attributes are accessed in the controller like: $this->flash, $this->request or $this->session. These are services defined in the services container from earlier (app/config/services.php). When they’re accessed the first time, they are injected as part of the controller. These services are shared, which means that we are always accessing the same instance regardless of the place where we invoke them. For instance, here we invoke the session service and then we store the user identity in the variable auth:

  1. <?php
  2. $this->session->set(
  3. 'auth',
  4. [
  5. 'id' => $user->id,
  6. 'name' => $user->name,
  7. ]
  8. );

Another important aspect of this section is how the user is validated as a valid one, first we validate whether the request has been made using method POST:

  1. <?php
  2. if ($this->request->isPost()) {
  3. // ...
  4. }

Then, we receive the parameters from the form:

  1. <?php
  2. $email = $this->request->getPost('email');
  3. $password = $this->request->getPost('password');

Now, we have to check if there is one user with the same username or email and password:

  1. <?php
  2. $user = Users::findFirst(
  3. [
  4. "(email = :email: OR username = :email:) AND password = :password: AND active = 'Y'",
  5. 'bind' => [
  6. 'email' => $email,
  7. 'password' => sha1($password),
  8. ]
  9. ]
  10. );

Note, the use of ‘bound parameters’, placeholders :email: and :password: are placed where values should be, then the values are ‘bound’ using the parameter bind. This safely replaces the values for those columns without having the risk of a SQL injection.

If the user is valid we register it in session and forwards him/her to the dashboard:

  1. <?php
  2. if ($user !== false) {
  3. $this->_registerSession($user);
  4. $this->flash->success(
  5. 'Welcome ' . $user->name
  6. );
  7. return $this->dispatcher->forward(
  8. [
  9. 'controller' => 'invoices',
  10. 'action' => 'index',
  11. ]
  12. );
  13. }

If the user does not exist we forward the user back again to action where the form is displayed:

  1. <?php
  2. return $this->dispatcher->forward(
  3. [
  4. 'controller' => 'session',
  5. 'action' => 'index',
  6. ]
  7. );

Securing the Backend

The backend is a private area where only registered users have access. Therefore, it is necessary to check that only registered users have access to these controllers. If you aren’t logged into the application and you try to access, for example, the products controller (which is private) you will see a screen like this:

Invo - 图3

Every time someone attempts to access any controller/action, the application verifies that the current role (in session) has access to it, otherwise it displays a message like the above and forwards the flow to the home page.

Now let’s find out how the application accomplishes this. The first thing to know is that there is a component called Dispatcher. It is informed about the route found by the Routing component. Then, it is responsible for loading the appropriate controller and execute the corresponding action method.

Normally, the framework creates the Dispatcher automatically. In our case, we want to perform a verification before executing the required action, checking if the user has access to it or not. To achieve this, we have replaced the component by creating a function in the bootstrap:

  1. <?php
  2. use Phalcon\Mvc\Dispatcher;
  3. // ...
  4. /**
  5. * MVC dispatcher
  6. */
  7. $di->set(
  8. 'dispatcher',
  9. function () {
  10. // ...
  11. $dispatcher = new Dispatcher();
  12. return $dispatcher;
  13. }
  14. );

We now have total control over the Dispatcher used in the application. Many components in the framework trigger events that allow us to modify their internal flow of operation. As the Dependency Injector component acts as glue for components, a new component called EventsManager allows us to intercept the events produced by a component, routing the events to listeners.

Events Management

The EventsManager allows us to attach listeners to a particular type of event. The type that interests us now is ‘dispatch’. The following code filters all events produced by the Dispatcher:

  1. <?php
  2. use Phalcon\Mvc\Dispatcher;
  3. use Phalcon\Events\Manager as EventsManager;
  4. $di->set(
  5. 'dispatcher',
  6. function () {
  7. // Create an events manager
  8. $eventsManager = new EventsManager();
  9. // Listen for events produced in the dispatcher using the Security plugin
  10. $eventsManager->attach(
  11. 'dispatch:beforeExecuteRoute',
  12. new SecurityPlugin()
  13. );
  14. // Handle exceptions and not-found exceptions using NotFoundPlugin
  15. $eventsManager->attach(
  16. 'dispatch:beforeException',
  17. new NotFoundPlugin()
  18. );
  19. $dispatcher = new Dispatcher();
  20. // Assign the events manager to the dispatcher
  21. $dispatcher->setEventsManager($eventsManager);
  22. return $dispatcher;
  23. }
  24. );

When an event called beforeExecuteRoute is triggered the following plugin will be notified:

  1. <?php
  2. /**
  3. * Check if the user is allowed to access certain action using the SecurityPlugin
  4. */
  5. $eventsManager->attach(
  6. 'dispatch:beforeExecuteRoute',
  7. new SecurityPlugin()
  8. );

When a beforeException is triggered then other plugin is notified:

  1. <?php
  2. /**
  3. * Handle exceptions and not-found exceptions using NotFoundPlugin
  4. */
  5. $eventsManager->attach(
  6. 'dispatch:beforeException',
  7. new NotFoundPlugin()
  8. );

SecurityPlugin is a class located at (app/plugins/SecurityPlugin.php). This class implements the method beforeExecuteRoute. This is the same name as one of the events produced in the Dispatcher:

  1. <?php
  2. use Phalcon\Events\Event;
  3. use Phalcon\Plugin;
  4. use Phalcon\Mvc\Dispatcher;
  5. class SecurityPlugin extends Plugin
  6. {
  7. // ...
  8. public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher)
  9. {
  10. // ...
  11. }
  12. }

The hook events always receive a first parameter that contains contextual information of the event produced ($event) and a second one that is the object that produced the event itself ($dispatcher). It is not mandatory that plugins extend the class Phalcon\Plugin, but by doing this they gain easier access to the services available in the application.

Now, we’re verifying the role in the current session, checking if the user has access using the ACL list. If the user does not have access we redirect to the home screen as explained before:

  1. <?php
  2. use Phalcon\Acl;
  3. use Phalcon\Events\Event;
  4. use Phalcon\Plugin;
  5. use Phalcon\Mvc\Dispatcher;
  6. class SecurityPlugin extends Plugin
  7. {
  8. // ...
  9. public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher)
  10. {
  11. // Check whether the 'auth' variable exists in session to define the active role
  12. $auth = $this->session->get('auth');
  13. if (!$auth) {
  14. $role = 'Guests';
  15. } else {
  16. $role = 'Users';
  17. }
  18. // Take the active controller/action from the dispatcher
  19. $controller = $dispatcher->getControllerName();
  20. $action = $dispatcher->getActionName();
  21. // Obtain the ACL list
  22. $acl = $this->getAcl();
  23. // Check if the Role have access to the controller (resource)
  24. $allowed = $acl->isAllowed($role, $controller, $action);
  25. if (!$allowed) {
  26. // If he doesn't have access forward him to the index controller
  27. $this->flash->error(
  28. "You don't have access to this module"
  29. );
  30. $dispatcher->forward(
  31. [
  32. 'controller' => 'index',
  33. 'action' => 'index',
  34. ]
  35. );
  36. // Returning 'false' we tell to the dispatcher to stop the current operation
  37. return false;
  38. }
  39. }
  40. }

Getting the ACL list

In the above example we have obtained the ACL using the method $this->getAcl(). This method is also implemented in the Plugin. Now we are going to explain step-by-step how we built the access control list (ACL):

  1. <?php
  2. use Phalcon\Acl;
  3. use Phalcon\Acl\Role;
  4. use Phalcon\Acl\Adapter\Memory as AclList;
  5. // Create the ACL
  6. $acl = new AclList();
  7. // The default action is DENY access
  8. $acl->setDefaultAction(
  9. Acl::DENY
  10. );
  11. // Register two roles, Users is registered users
  12. // and guests are users without a defined identity
  13. $roles = [
  14. 'users' => new Role('Users'),
  15. 'guests' => new Role('Guests'),
  16. ];
  17. foreach ($roles as $role) {
  18. $acl->addRole($role);
  19. }

Now, we define the resources for each area respectively. Controller names are resources and their actions are accesses for the resources:

  1. <?php
  2. use Phalcon\Acl\Resource;
  3. // ...
  4. // Private area resources (backend)
  5. $privateResources = [
  6. 'companies' => ['index', 'search', 'new', 'edit', 'save', 'create', 'delete'],
  7. 'products' => ['index', 'search', 'new', 'edit', 'save', 'create', 'delete'],
  8. 'producttypes' => ['index', 'search', 'new', 'edit', 'save', 'create', 'delete'],
  9. 'invoices' => ['index', 'profile'],
  10. ];
  11. foreach ($privateResources as $resourceName => $actions) {
  12. $acl->addResource(
  13. new Resource($resourceName),
  14. $actions
  15. );
  16. }
  17. // Public area resources (frontend)
  18. $publicResources = [
  19. 'index' => ['index'],
  20. 'about' => ['index'],
  21. 'register' => ['index'],
  22. 'errors' => ['show404', 'show500'],
  23. 'session' => ['index', 'register', 'start', 'end'],
  24. 'contact' => ['index', 'send'],
  25. ];
  26. foreach ($publicResources as $resourceName => $actions) {
  27. $acl->addResource(
  28. new Resource($resourceName),
  29. $actions
  30. );
  31. }

The ACL now knows about the existing controllers and their related actions. Role Users has access to all the resources of both frontend and backend. The role Guests only has access to the public area:

  1. <?php
  2. // Grant access to public areas to both users and guests
  3. foreach ($roles as $role) {
  4. foreach ($publicResources as $resource => $actions) {
  5. $acl->allow(
  6. $role->getName(),
  7. $resource,
  8. '*'
  9. );
  10. }
  11. }
  12. // Grant access to private area only to role Users
  13. foreach ($privateResources as $resource => $actions) {
  14. foreach ($actions as $action) {
  15. $acl->allow(
  16. 'Users',
  17. $resource,
  18. $action
  19. );
  20. }
  21. }

Working with the CRUD

Backends usually provide forms to allow users to manipulate data. Continuing the explanation of INVO, we now address the creation of CRUDs, a very common task that Phalcon will facilitate you using forms, validations, paginators and more.

Most options that manipulate data in INVO (companies, products and types of products) were developed using a basic and common CRUD (Create, Read, Update and Delete). Each CRUD contains the following files:

  1. invo/
  2. app/
  3. controllers/
  4. ProductsController.php
  5. models/
  6. Products.php
  7. forms/
  8. ProductsForm.php
  9. views/
  10. products/
  11. edit.volt
  12. index.volt
  13. new.volt
  14. search.volt

Each controller has the following actions:

  1. <?php
  2. class ProductsController extends ControllerBase
  3. {
  4. /**
  5. * The start action, it shows the 'search' view
  6. */
  7. public function indexAction()
  8. {
  9. // ...
  10. }
  11. /**
  12. * Execute the 'search' based on the criteria sent from the 'index'
  13. * Returning a paginator for the results
  14. */
  15. public function searchAction()
  16. {
  17. // ...
  18. }
  19. /**
  20. * Shows the view to create a 'new' product
  21. */
  22. public function newAction()
  23. {
  24. // ...
  25. }
  26. /**
  27. * Shows the view to 'edit' an existing product
  28. */
  29. public function editAction()
  30. {
  31. // ...
  32. }
  33. /**
  34. * Creates a product based on the data entered in the 'new' action
  35. */
  36. public function createAction()
  37. {
  38. // ...
  39. }
  40. /**
  41. * Updates a product based on the data entered in the 'edit' action
  42. */
  43. public function saveAction()
  44. {
  45. // ...
  46. }
  47. /**
  48. * Deletes an existing product
  49. */
  50. public function deleteAction($id)
  51. {
  52. // ...
  53. }
  54. }

The Search Form

Every CRUD starts with a search form. This form shows each field that the table has (products), allowing the user to create a search criteria for any field. The products table has a relationship with the table products_types. In this case, we previously queried the records in this table in order to facilitate the search by that field:

  1. <?php
  2. /**
  3. * The start action, it shows the 'search' view
  4. */
  5. public function indexAction()
  6. {
  7. $this->persistent->searchParams = null;
  8. $this->view->form = new ProductsForm();
  9. }

An instance of the ProductsForm form (app/forms/ProductsForm.php) is passed to the view. This form defines the fields that are visible to the user:

  1. <?php
  2. use Phalcon\Forms\Form;
  3. use Phalcon\Forms\Element\Text;
  4. use Phalcon\Forms\Element\Hidden;
  5. use Phalcon\Forms\Element\Select;
  6. use Phalcon\Validation\Validator\Email;
  7. use Phalcon\Validation\Validator\PresenceOf;
  8. use Phalcon\Validation\Validator\Numericality;
  9. class ProductsForm extends Form
  10. {
  11. /**
  12. * Initialize the products form
  13. */
  14. public function initialize($entity = null, $options = [])
  15. {
  16. if (!isset($options['edit'])) {
  17. $element = new Text('id');
  18. $element->setLabel('Id');
  19. $this->add($element);
  20. } else {
  21. $this->add(new Hidden('id'));
  22. }
  23. $name = new Text('name');
  24. $name->setLabel('Name');
  25. $name->setFilters(
  26. [
  27. 'striptags',
  28. 'string',
  29. ]
  30. );
  31. $name->addValidators(
  32. [
  33. new PresenceOf(
  34. [
  35. 'message' => 'Name is required',
  36. ]
  37. )
  38. ]
  39. );
  40. $this->add($name);
  41. $type = new Select(
  42. 'profilesId',
  43. ProductTypes::find(),
  44. [
  45. 'using' => [
  46. 'id',
  47. 'name',
  48. ],
  49. 'useEmpty' => true,
  50. 'emptyText' => '...',
  51. 'emptyValue' => '',
  52. ]
  53. );
  54. $this->add($type);
  55. $price = new Text('price');
  56. $price->setLabel('Price');
  57. $price->setFilters(
  58. [
  59. 'float',
  60. ]
  61. );
  62. $price->addValidators(
  63. [
  64. new PresenceOf(
  65. [
  66. 'message' => 'Price is required',
  67. ]
  68. ),
  69. new Numericality(
  70. [
  71. 'message' => 'Price is required',
  72. ]
  73. ),
  74. ]
  75. );
  76. $this->add($price);
  77. }
  78. }

The form is declared using an object-oriented scheme based on the elements provided by the forms component. Every element follows almost the same structure:

  1. <?php
  2. // Create the element
  3. $name = new Text('name');
  4. // Set its label
  5. $name->setLabel('Name');
  6. // Before validating the element apply these filters
  7. $name->setFilters(
  8. [
  9. 'striptags',
  10. 'string',
  11. ]
  12. );
  13. // Apply this validators
  14. $name->addValidators(
  15. [
  16. new PresenceOf(
  17. [
  18. 'message' => 'Name is required',
  19. ]
  20. )
  21. ]
  22. );
  23. // Add the element to the form
  24. $this->add($name);

Other elements are also used in this form:

  1. <?php
  2. // Add a hidden input to the form
  3. $this->add(
  4. new Hidden('id')
  5. );
  6. // ...
  7. $productTypes = ProductTypes::find();
  8. // Add a HTML Select (list) to the form
  9. // and fill it with data from 'product_types'
  10. $type = new Select(
  11. 'profilesId',
  12. $productTypes,
  13. [
  14. 'using' => [
  15. 'id',
  16. 'name',
  17. ],
  18. 'useEmpty' => true,
  19. 'emptyText' => '...',
  20. 'emptyValue' => '',
  21. ]
  22. );

Note that ProductTypes::find() contains the data necessary to fill the SELECT tag using Phalcon\Tag::select(). Once the form is passed to the view, it can be rendered and presented to the user:

  1. {{ form('products/search') }}
  2. <h2>
  3. Search products
  4. </h2>
  5. <fieldset>
  6. {% for element in form %}
  7. <div class='control-group'>
  8. {{ element.label(['class': 'control-label']) }}
  9. <div class='controls'>
  10. {{ element }}
  11. </div>
  12. </div>
  13. {% endfor %}
  14. <div class='control-group'>
  15. {{ submit_button('Search', 'class': 'btn btn-primary') }}
  16. </div>
  17. </fieldset>
  18. {{ endForm() }}

This produces the following HTML:

  1. <form action='/invo/products/search' method='post'>
  2. <h2>
  3. Search products
  4. </h2>
  5. <fieldset>
  6. <div class='control-group'>
  7. <label for='id' class='control-label'>Id</label>
  8. <div class='controls'>
  9. <input type='text' id='id' name='id' />
  10. </div>
  11. </div>
  12. <div class='control-group'>
  13. <label for='name' class='control-label'>Name</label>
  14. <div class='controls'>
  15. <input type='text' id='name' name='name' />
  16. </div>
  17. </div>
  18. <div class='control-group'>
  19. <label for='profilesId' class='control-label'>profilesId</label>
  20. <div class='controls'>
  21. <select id='profilesId' name='profilesId'>
  22. <option value=''>...</option>
  23. <option value='1'>Vegetables</option>
  24. <option value='2'>Fruits</option>
  25. </select>
  26. </div>
  27. </div>
  28. <div class='control-group'>
  29. <label for='price' class='control-label'>Price</label>
  30. <div class='controls'>
  31. <input type='text' id='price' name='price' />
  32. </div>
  33. </div>
  34. <div class='control-group'>
  35. <input type='submit' value='Search' class='btn btn-primary' />
  36. </div>
  37. </fieldset>
  38. </form>

When the form is submitted, the search action is executed in the controller performing the search based on the data entered by the user.

The search action has two behaviors. When accessed via POST, it performs a search based on the data sent from the form but when accessed via GET it moves the current page in the paginator. To differentiate HTTP methods, we check it using the Request component:

<?php

/**
 * Execute the 'search' based on the criteria sent from the 'index'
 * Returning a paginator for the results
 */
public function searchAction()
{
    if ($this->request->isPost()) {
        // Create the query conditions
    } else {
        // Paginate using the existing conditions
    }

    // ...
}

With the help of Phalcon\Mvc\Model\Criteria, we can create the search conditions intelligently based on the data types and values sent from the form:

<?php

$query = Criteria::fromInput(
    $this->di,
    'Products',
    $this->request->getPost()
);

This method verifies which values are different from ‘’ (empty string) and null and takes them into account to create the search criteria:

  • If the field data type is text or similar (char, varchar, text, etc.) It uses an SQL like operator to filter the results.
  • If the data type is not text or similar, it’ll use the operator =.Additionally, Criteria ignores all the $_POST variables that do not match any field in the table. Values are automatically escaped using bound parameters.

Now, we store the produced parameters in the controller’s session bag:

<?php

$this->persistent->searchParams = $query->getParams();

A session bag, is a special attribute in a controller that persists between requests using the session service. When accessed, this attribute injects a Phalcon\Session\Bag instance that is independent in each controller.

Then, based on the built params we perform the query:

<?php

$products = Products::find($parameters);

if (count($products) === 0) {
    $this->flash->notice(
        'The search did not found any products'
    );

    return $this->dispatcher->forward(
        [
            'controller' => 'products',
            'action'     => 'index',
        ]
    );
}

If the search doesn’t return any product, we forward the user to the index action again. Let’s pretend the search returned results, then we create a paginator to navigate easily through them:

<?php

use Phalcon\Paginator\Adapter\Model as Paginator;

// ...

$paginator = new Paginator(
    [
        'data'  => $products,   // Data to paginate
        'limit' => 5,           // Rows per page
        'page'  => $numberPage, // Active page
    ]
);

// Get active page in the paginator
$page = $paginator->paginate();

Finally we pass the returned page to view:

<?php

$this->view->page = $page;

In the view (app/views/products/search.volt), we traverse the results corresponding to the current page, showing every row in the current page to the user:


{% for product in page.items %}
    {% if loop.first %}
        <table>
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Product Type</th>
                    <th>Name</th>
                    <th>Price</th>
                    <th>Active</th>
                </tr>
            </thead>
            <tbody>
    {% endif %}

    <tr>
        <td>
            {{ product.id }}
        </td>

        <td>
            {{ product.getProductTypes().name }}
        </td>

        <td>
            {{ product.name }}
        </td>

        <td>
            {{ '%.2f'|format(product.price) }}
        </td>

        <td>
            {{ product.getActiveDetail() }}
        </td>

        <td width='7%'>
            {{ link_to('products/edit/' ~ product.id, 'Edit') }}
        </td>

        <td width='7%'>
            {{ link_to('products/delete/' ~ product.id, 'Delete') }}
        </td>
    </tr>

    {% if loop.last %}
            </tbody>
            <tbody>
                <tr>
                    <td colspan='7'>
                        <div>
                            {{ link_to('products/search', 'First') }}
                            {{ link_to('products/search?page=' ~ page.before, 'Previous') }}
                            {{ link_to('products/search?page=' ~ page.next, 'Next') }}
                            {{ link_to('products/search?page=' ~ page.last, 'Last') }}
                            <span class='help-inline'>{{ page.current }} of {{ page.total_pages }}</span>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>
    {% endif %}
{% else %}
    No products are recorded
{% endfor %}

There are many things in the above example that worth detailing. First of all, active items in the current page are traversed using a Volt’s for. Volt provides a simpler syntax for a PHP foreach.


{% for product in page.items %}

Which in PHP is the same as:

<?php foreach ($page->items as $product) { ?>

The whole for block provides the following:


{% for product in page.items %}
    {% if loop.first %}
        Executed before the first product in the loop
    {% endif %}

    Executed for every product of page.items

    {% if loop.last %}
        Executed after the last product is loop
    {% endif %}
{% else %}
    Executed if page.items does not have any products
{% endfor %}

Now you can go back to the view and find out what every block is doing. Every field in product is printed accordingly:


<tr>
    <td>
        {{ product.id }}
    </td>

    <td>
        {{ product.productTypes.name }}
    </td>

    <td>
        {{ product.name }}
    </td>

    <td>
        {{ '%.2f'|format(product.price) }}
    </td>

    <td>
        {{ product.getActiveDetail() }}
    </td>

    <td width='7%'>
        {{ link_to('products/edit/' ~ product.id, 'Edit') }}
    </td>

    <td width='7%'>
        {{ link_to('products/delete/' ~ product.id, 'Delete') }}
    </td>
</tr>

As we seen before using product.id is the same as in PHP as doing: $product->id, we made the same with product.name and so on. Other fields are rendered differently, for instance, let’s focus in product.productTypes.name. To understand this part, we have to check the Products model (app/models/Products.php):

<?php

use Phalcon\Mvc\Model;

/**
 * Products
 */
class Products extends Model
{
    // ...

    /**
     * Products initializer
     */
    public function initialize()
    {
        $this->belongsTo(
            'product_types_id',
            'ProductTypes',
            'id',
            [
                'reusable' => true,
            ]
        );
    }

    // ...
}

A model can have a method called initialize(), this method is called once per request and it serves the ORM to initialize a model. In this case, ‘Products’ is initialized by defining that this model has a one-to-many relationship to another model called ‘ProductTypes’.

<?php

$this->belongsTo(
    'product_types_id',
    'ProductTypes',
    'id',
    [
        'reusable' => true,
    ]
);

Which means, the local attribute product_types_id in Products has an one-to-many relation to the ProductTypes model in its attribute id. By defining this relationship we can access the name of the product type by using:


<td>{{ product.productTypes.name }}</td>

The field price is printed by its formatted using a Volt filter:


<td>{{ '%.2f'|format(product.price) }}</td>

In plain PHP, this would be:

<?php echo sprintf('%.2f', $product->price) ?>

Printing whether the product is active or not uses a helper implemented in the model:


<td>{{ product.getActiveDetail() }}</td>

This method is defined in the model.

Creating and Updating Records

Now let’s see how the CRUD creates and updates records. From the new and edit views, the data entered by the user is sent to the create and save actions that perform actions of creating and updating products, respectively.

In the creation case, we recover the data submitted and assign them to a new Products instance:

<?php

/**
 * Creates a product based on the data entered in the 'new' action
 */
public function createAction()
{
    if (!$this->request->isPost()) {
        return $this->dispatcher->forward(
            [
                'controller' => 'products',
                'action'     => 'index',
            ]
        );
    }

    $form = new ProductsForm();

    $product = new Products();

    $product->id               = $this->request->getPost('id', 'int');
    $product->product_types_id = $this->request->getPost('product_types_id', 'int');
    $product->name             = $this->request->getPost('name', 'striptags');
    $product->price            = $this->request->getPost('price', 'double');
    $product->active           = $this->request->getPost('active');

    // ...
}

Remember the filters we defined in the Products form? Data is filtered before being assigned to the object $product. This filtering is optional; the ORM also escapes the input data and performs additional casting according to the column types:

<?php

// ...

$name = new Text('name');

$name->setLabel('Name');

// Filters for name
$name->setFilters(
    [
        'striptags',
        'string',
    ]
);

// Validators for name
$name->addValidators(
    [
        new PresenceOf(
            [
                'message' => 'Name is required',
            ]
        )
    ]
);

$this->add($name);

When saving, we’ll know whether the data conforms to the business rules and validations implemented in the form ProductsForm form (app/forms/ProductsForm.php):

<?php

// ...

$form = new ProductsForm();

$product = new Products();

// Validate the input
$data = $this->request->getPost();

if (!$form->isValid($data, $product)) {
    $messages = $form->getMessages();

    foreach ($messages as $message) {
        $this->flash->error($message);
    }

    return $this->dispatcher->forward(
        [
            'controller' => 'products',
            'action'     => 'new',
        ]
    );
}

Finally, if the form does not return any validation message we can save the product instance:

<?php

// ...

if ($product->save() === false) {
    $messages = $product->getMessages();

    foreach ($messages as $message) {
        $this->flash->error($message);
    }

    return $this->dispatcher->forward(
        [
            'controller' => 'products',
            'action'     => 'new',
        ]
    );
}

$form->clear();

$this->flash->success(
    'Product was created successfully'
);

return $this->dispatcher->forward(
    [
        'controller' => 'products',
        'action'     => 'index',
    ]
);

Now, in the case of updating a product, we must first present the user with the data that is currently in the edited record:

<?php

/**
 * Edits a product based on its id
 */
public function editAction($id)
{
    if (!$this->request->isPost()) {
        $product = Products::findFirstById($id);

        if (!$product) {
            $this->flash->error(
                'Product was not found'
            );

            return $this->dispatcher->forward(
                [
                    'controller' => 'products',
                    'action'     => 'index',
                ]
            );
        }

        $this->view->form = new ProductsForm(
            $product,
            [
                'edit' => true,
            ]
        );
    }
}

The data found is bound to the form by passing the model as first parameter. Thanks to this, the user can change any value and then sent it back to the database through to the save action:

<?php

/**
 * Updates a product based on the data entered in the 'edit' action
 */
public function saveAction()
{
    if (!$this->request->isPost()) {
        return $this->dispatcher->forward(
            [
                'controller' => 'products',
                'action'     => 'index',
            ]
        );
    }

    $id = $this->request->getPost('id', 'int');

    $product = Products::findFirstById($id);

    if (!$product) {
        $this->flash->error(
            'Product does not exist'
        );

        return $this->dispatcher->forward(
            [
                'controller' => 'products',
                'action'     => 'index',
            ]
        );
    }

    $form = new ProductsForm();

    $data = $this->request->getPost();

    if (!$form->isValid($data, $product)) {
        $messages = $form->getMessages();

        foreach ($messages as $message) {
            $this->flash->error($message);
        }

        return $this->dispatcher->forward(
            [
                'controller' => 'products',
                'action'     => 'new',
            ]
        );
    }

    if ($product->save() === false) {
        $messages = $product->getMessages();

        foreach ($messages as $message) {
            $this->flash->error($message);
        }

        return $this->dispatcher->forward(
            [
                'controller' => 'products',
                'action'     => 'new',
            ]
        );
    }

    $form->clear();

    $this->flash->success(
        'Product was updated successfully'
    );

    return $this->dispatcher->forward(
        [
            'controller' => 'products',
            'action'     => 'index',
        ]
    );
}

User Components

All the UI elements and visual style of the application has been achieved mostly through Bootstrap. Some elements, such as the navigation bar changes according to the state of the application. For example, in the upper right corner, the link Log in / Sign Up changes to Log out if a user is logged into the application.

This part of the application is implemented in the component Elements (app/library/Elements.php).

<?php

use Phalcon\Plugin;

class Elements extends Plugin
{
    public function getMenu()
    {
        // ...
    }

    public function getTabs()
    {
        // ...
    }
}

This class extends the Phalcon\Plugin. It is not imposed to extend a component with this class, but it helps to get access more quickly to the application services. Now, we are going to register our first user component in the services container:

<?php

// Register a user component
$di->set(
    'elements',
    function () {
        return new Elements();
    }
);

As controllers, plugins or components within a view, this component also has access to the services registered in the container and by just accessing an attribute with the same name as a previously registered service:


<div class='navbar navbar-fixed-top'>
    <div class='navbar-inner'>
        <div class='container'>
            <a class='btn btn-navbar' data-toggle='collapse' data-target='.nav-collapse'>
                <span class='icon-bar'></span>
                <span class='icon-bar'></span>
                <span class='icon-bar'></span>
            </a>

            <a class='brand' href='#'>INVO</a>

            {{ elements.getMenu() }}
        </div>
    </div>
</div>

<div class='container'>
    {{ content() }}

    <hr>

    <footer>
        <p>&copy; Company 2017</p>
    </footer>
</div>

The important part is:


{{ elements.getMenu() }}

Changing the Title Dynamically

When you browse between one option and another will see that the title changes dynamically indicating where we are currently working. This is achieved in each controller initializer:

<?php

class ProductsController extends ControllerBase
{
    public function initialize()
    {
        // Set the document title
        $this->tag->setTitle(
            'Manage your product types'
        );

        parent::initialize();
    }

    // ...
}

Note, that the method parent::initialize() is also called, it adds more data to the title:

<?php

use Phalcon\Mvc\Controller;

class ControllerBase extends Controller
{
    protected function initialize()
    {
        // Prepend the application name to the title
        $this->tag->prependTitle('INVO | ');
    }

    // ...
}

Finally, the title is printed in the main view (app/views/index.volt):

<!DOCTYPE html>
<html>
    <head>
        <?php echo $this->tag->getTitle(); ?>
    </head>

    <!-- ... -->
</html>