20 min read

In this article written by Serghei Iakovlev and David Schissler, authors of the book Phalcon Cookbook , we will cover:

(For more resources related to this topic, see here.)

  • Choosing the best place for an implementation
  • Automation of routine tasks
  • Creating the application structure by using code generation tools

Introduction

In this article you will learn that, often, by creating new projects, developers can face some issues such as what components should they create, where to place them in the application structure, what would each component implement, what naming convention to follow, and so on. Actually, creating custom components isn’t a difficult matter; we will sort it out in this article. We will create our own component which will display different menus on your site depending on where we are in the application.

From one project to another, the developer’s work is usually repeated. This holds true for tasks such as creating the project structure, configuration, creating data models, controllers, views, and so on. For those tasks, we will discover the power of Phalcon Developer Tools and how to use them. You will learn how to create an application skeleton by using one command, and even how to create a fully functional application prototype in less than 10 minutes without writing a single line of code.

Developers often come up against a situation where they need to create a lot of predefined code templates. Until you are really familiar with the framework it can be useful for you to do everything manually. But anyway all of us would like to reduce repetitive tasks. Phalcon tries to help you by providing an easy and at the same time flexible code generation tool named Phalcon Developer Tools. These tools help you simplify the creation of CRUD components for a regular application. Therefore, you can create working code in a matter of seconds without creating the code yourself.

Often, when creating an application using a framework, we need to extend or add functionality to the framework components. We don’t have to reinvent the wheel by rewriting those components. We can use class inheritance and extensibility, but often this approach does not work. In such cases, it is better to use additional layers between the main application and the framework by creating a middleware layer.

The term middleware has a wide range of meanings, but in the context of PHP web applications it means code, which will be called in turns by each request.

We will look into the main principles of creating and using middleware in your application. We will not get into each solution in depth, but instead we will work with tasks that are common for most projects, and implementations extending Phalcon.

Choosing the best place for an implementation

Let’s pretend you want to add a custom component. As the case may be, this component allows to change your site navigation menu. For example, when you have a Sign In link on your navigation menu and you are logged in, that link needs to change to Sign Out. Then you’re asking yourself where is the best place in the project to put the code, where to place the files, how to name the classes, how to make them autoload by the autoloader.

Getting ready…

For successful implementation of this recipe you must have your application deployed. By this we mean that you need to have a web server installed and configured for handling requests to your application, an application must be able to receive requests, and have implemented the necessary components such as Controllers, Views, and a bootstrap file. For this recipe, we assume that our application is located in the apps directory. If this is not the case, you should change this part of the path in the examples shown in this article.

How to do it…

Follow these steps to complete this recipe:

  1. Create the /library/ directory app, if you haven’t got one, where user components will be stored.
  2. Next, create the Elements (app/library/Elements.php) component. This class extends PhalconMvcUserComponent. Generally, it is not necessary, but it helps get access to application services quickly. The contents of Elements should be:
    <?php
    
    namespace Library;
    
    use PhalconMvcUserComponent;
    use PhalconMvcViewSimple as View;
    
    class Elements extends Component
    {
      public function __construct()
      {
        // ...
      }
    
      public function getMenu()
      {
        // ...
      }
    }
  3. Now we register this class in the Dependency Injection Container. We use a shared instance in order to prevent creating new instances by each service resolving:
    $di->setShared('elements', function () {
        return new LibraryElements();
    });
  4. If your Session service is not initialized yet, it’s time to do it in your bootstrap file. We use a shared instance for the following reasons:
    $di->setShared('session', function () {
        $session = new PhalconSessionAdapterFiles();
        $session->start();
    
        return $session;
    });
  5. Create the templates directory within the directory with your views/templates.
  6. Then you need to tell the class autoloader about a new namespace, which we have just entered. Let’s do it in the following way:
    $loader->registerNamespaces([
        // The APP_PATH constant should point
        // to the project's root
        'Library' => APP_PATH . '/apps/library/',
        // ...
    ]);
  7. Add the following code right after the tag body in the main layout of your application:
    <div class="container">
      <div class="navbar navbar-inverse">
        <div class="container-fluid">
          <div class="navbar-header">
            <button type="button" class="navbar-toggle 
    collapsed" data-toggle="collapse" data-target="#blog-top-
    menu" aria-expanded="false">
              <span class="sr-only">Toggle navigation</span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">Blog 24</a>
          </div>
          <?php echo $this->elements->getMenu(); ?>
        </div>
      </div>
    </div>
  8. Next, we need to create a template for displaying your top menu. Let’s create it in views/templates/topMenu.phtml:
    <div class="collapse navbar-collapse" id="blog-top-menu">
      <ul class="nav navbar-nav">
        <li class="active">
          <a href="#">Home</a>
        </li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li>
          <?php if ($this->session->get('identity')): ?>
            <a href="#">Sign Out</a>
          <?php else: ?>
            <a href="#">Sign In</a>
          <?php endif; ?>
        </li>
      </ul>
    </div>
  9. Now, let’s put the component to work. First, create the protected field $simpleView and initialize it in the controller:
    public function __construct()
    {
        $this->simpleView =  new View();
        $this->simpleView->setDI($this->getDI());
    }
  10. And finally, implement the getMenu method as follows:
    public function getMenu()
    {
        $this->simpleView->setViewsDir($this->view-
    >getViewsDir());
    
        return $this->simpleView->render('templates/topMenu');
    }
  11. Open the main page of your site to ensure that your top menu is rendered.

How it works…

The main idea of our component is to generate a top menu, and to display the correct menu option depending on the situation, meaning whether the user is authorized or not.

We create the user component, Elements, putting it in a place specially designed for the purpose. Of course, when creating the directory library and placing a new class there, we should tell the autoloader about a new namespace. This is exactly what we have done.

However, we should take note of one important peculiarity. We should note that if you want to get access to your components quickly even in HTML templates like $this->elements, then you should put the components in the DI container. Therefore, we put our component, LibraryElements, in the container named elements.

Since our component inherits PhalconMvcUserComponent, we are able to access all registered application services just by their names. For example, the following instruction, $this->view can be written in a long form, $this->getDi()->getShared(‘view’), but the first one is obviously more concise.

Although not necessary, for application structure purposes, it is better to use a separate directory for different views not connected straight to specific controllers and actions. In our case, the directory views/templates serves for this purpose. We create a HTML template for menu rendering and place it in views/templates/topMenu.phtml.

When using the method getMenu, our component will render the view topMenu.phtml and return HTML. In the method getMenu, we get the current path for all our views and set it for the PhalconMvcViewSimple component, created earlier in the constructor. In the view topMenu we access to the session component, which earlier we placed in the DI container. By generating the menu, we check whether the user is authorized or not. In the former case, we use the Sign out menu item, in the latter case we display the menu item with an invitation to Sign in.

Automation of routine tasks

The Phalcon project provides you with a great tool named Developer Tools. It helps automating repeating tasks, by means of code generation of components as well as a project skeleton. Most of the components of your application can be created only with one command. In this recipe, we will consider in depth the Developer Tools installation and configuration.

Getting Ready…

Before you begin to work on this recipe, you should have a DBMS configured, a web server installed and configured for handling requests from your application. You may need to configure a virtual host (this is optional) for your application which will receive and handle requests. You should be able to open your newly-created project in a browser at http://{your-host-here}/appname or http://{your-host-here}/, where your-host-here is the name of your project.

You should have Git installed, too.

In this recipe, we assume that your operating system is Linux. Developer Tools installation instructions for Mac OS X and Windows will be similar. You can find the link to the complete documentation for Mac OS X and Windows at the end of this recipe.

We used the Terminal to create the database tables, and chose MySQL as our RDBMS. Your setup might vary. The choice of a tool for creating a table in your database, as well as a particular DBMS, is yours. Note that syntax for creating a table by using other DBMSs than MySQL may vary.

How to do it…

Follow these steps to complete this recipe:

  1. Clone Developer Tools in your home directory:
    git clone [email protected]:phalcon/phalcon-devtools.git devtools
  2. Go to the newly created directory devtools, run the./phalcon.sh command, and wait for a message about successful installation completion:
    $ ./phalcon.sh
    Phalcon Developer Tools Installer
    Make sure phalcon.sh is in the same dir as phalcon.php and that you are running this with sudo or as root.
    Installing Devtools...
    Working dir is: /home/user/devtools
    Generating symlink...
    Done. Devtools installed!
  3. Run the phalcon command without arguments to see the available command list and your current Phalcon version:
    $ phalcon
    
    Phalcon DevTools (3.0.0)
    
    Available commands:
      commands         (alias of: list, enumerate)
      controller       (alias of: create-controller)
      model            (alias of: create-model)
      module           (alias of: create-module)
      all-models       (alias of: create-all-models)
      project          (alias of: create-project)
      scaffold         (alias of: create-scaffold)
      migration        (alias of: create-migration)
      webtools         (alias of: create-webtools)
  4. Now, let’s create our project. Go to the folder where you plan to create the project and run the following command:
    $ phalcon project myapp simple
  5. Open the website which you have just created with the previous command in your browser. You should see a message about the successful installation.
  6. Create a database for your project:
    mysql -e 'CREATE DATABASE myapp' -u root -p
  7. You will need to configure our application to connect to the database. Open the file app/config/config.php and correct the database connection configuration. Draw attention to the baseUri: parameter if you have not configured your virtual host according to your project. The value of this parameter must be / or /myapp/. As the result, your configuration file must look like this:
    <?php
    
    use PhalconConfig;
    
    defined('APP_PATH') || define('APP_PATH', realpath('.'));
    
    return new Config([
      'database' => [
        'adapter'     => 'Mysql',
        'host'        => 'localhost',
        'username'    => 'root',
        'password'    => '',
        'dbname'      => 'myapp',
        'charset'     => 'utf8',
      ],
      'application' => [
        'controllersDir' => APP_PATH . '/app/controllers/',
        'modelsDir'      => APP_PATH . '/app/models/',
        'migrationsDir'  => APP_PATH . '/app/migrations/',
        'viewsDir'       => APP_PATH . '/app/views/',
        'pluginsDir'     => APP_PATH . '/app/plugins/',
        'libraryDir'     => APP_PATH . '/app/library/',
        'cacheDir'       => APP_PATH . '/app/cache/',
        'baseUri'        => '/myapp/',
      ]
    ]);
  8. Now, after you have configured the database access, let’s create a users table in your database. Create the users table and fill it with the primary data:
    CREATE TABLE `users` (
      `id` INT(11) unsigned NOT NULL AUTO_INCREMENT,
      `email` VARCHAR(128) NOT NULL,
      `first_name` VARCHAR(64) DEFAULT NULL,
      `last_name` VARCHAR(64) DEFAULT NULL,
      `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP 
    ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      UNIQUE KEY `users_email` (`email`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    INSERT INTO `users` (`email`, `first_name`, `last_name`) 
    VALUES
    ('[email protected]', 'John', 'Doe'),
    ('[email protected]', 'Janie', 'Doe');
  9. After that we need to create a new controller, UsersController. This controller must provide us with the main CRUD actions on the Users model and, if necessary, display data with the appropriate views. Lets do it with just one command:
    $ phalcon scaffold users
  10. In your web browser, open the URL associated with your newly created resource User and try to find one of the users of our database table at http://{your-host-here}/appname/users (or http://{your-host-here}/users, depending on how you have configured your server for application request handling.
  11. Finally, open your project in your file manager to see all the project structure created with Developer Tools:
    +-- app
    ¦   +-- cache
    ¦   +-- config
    ¦   +-- controllers
    ¦   +-- library
    ¦   +-- migrations
    ¦   +-- models
    ¦   +-- plugins
    ¦   +-- schemas
    ¦   +-- views
    ¦       +-- index
    ¦       +-- layouts
    ¦       +-- users
    +-- public
        +-- css
        +-- files
        +-- img
        +-- js
        +-- temp

How it works…

We installed Developer Tools with only two commands, git clone and ./phalcon. This is all we need to start using this powerful code generation tool.

Next, using only one command, we created a fully functional application environment. At this stage, the application doesn’t represent something outstanding in terms of features, but we have saved time from manually creating the application structure. Developer Tools did that for you! If after this command completion you examine your newly created project, you may notice that the primary application configuration has been generated also, including the bootstrap file. Actually, the phalcon project command has additional options that we have not demonstrated in this recipe. We are focusing on the main commands. Enter the command help to see all available project creating options:

$ phalcon project help

In the modern world, you can hardly find a web application which works without access to a database. Our application isn’t an exception. We created a database for our application, and then we created a users table and filled it with primary data. Of course, we need to supply our application with what we have done in the app/config/config.php file with the database access parameters as well as the database name.

After the successful database and table creation, we used the scaffold command for the pre-defined code template generation, particularly the Users controller with all main CRUD actions, all the necessary views, and the Users model. As before, we have used only one command to generate all those files.

Phalcon Developer Tools is equipped with a good amount of different useful tools. To see all the available options, you can use the command help. We have taken only a few minutes to create the first version of our application. Instead of spending time with repetitive tasks (such as the creation of the application skeleton), we can now use that time to do more exciting tasks.

Phalcon Developer Tools helps us save time where possible. But wait, there is more! The project is evolving, and it becomes more featureful day by day. If you have any problems you can always visit the project on GitHub https://github.com/phalcon/phalcon-devtools and search for a solution.

There’s more…

You can find more information on Phalcon Developer Tools installation for Windows and OS X at: https://docs.phalconphp.com/en/latest/reference/tools.html. More detailed information on web server configuration can be found at: https://docs.phalconphp.com/en/latest/reference/install.html

Creating the application structure by using code generation tools

In the following recipe, we will discuss available code generation tools that can be used for creating a multi-module application. We don’t need to create the application structure and main components manually.

Getting Ready…

Before you begin, you need to have Git installed, as well as any DBMS (for example, MySQL, PostgreSQL, SQLite, and the like), the Phalcon PHP extension (usually it is named php5-phalcon) and a PHP extension, which offers database connectivity support using PDO (for example, php5-mysql, php5-pgsql or php5-sqlite, and the like). You also need to be able to create tables in your database.

To accomplish the following recipe, you will require Phalcon Developer Tools. If you already have it installed, you may skip the first three steps related to the installation and go to the fourth step.

In this recipe, we assume that your operating system is Linux. Developer Tools installation instructions for Mac OS X and Windows will be similar. You can find the link to the complete documentation for Mac OS X and Windows at the end of this recipe.

We used the Terminal to create the database tables, and chose MySQL as our RDBMS. Your setup might vary. The choice of a tool for creating a table in your database, as well as particular DBMS, is yours. Note that syntax for creating a table by using other DBMSs than MySQL may vary.

How to do it…

Follow these steps to complete this recipe:

  1. First you need to decide where you will install Developer Tools. Put the case that you are going to place Developer Tools in your home directory. Then, go to your home directory and run the following command:
    git clone [email protected]:phalcon/phalcon-devtools.git
  2. Now browse to the newly created phalcon-devtools directory and run the following command to ensure that there are no problems:
    ./phalcon.sh
  3. Now, as far as you have Developer Tools installed, browse to the directory, where you intend to create your project, and run the following command:
    phalcon project blog modules
  4. If there were no errors during the previous step, then create a Help Controller by running the following command:
    phalcon controller Help --base-class=ControllerBase —
    namespace=Blog\Frontend\Controllers
  5. Open the newly generated HelpController in the apps/frontend/controllers/HelpController.php file to ensure that you have the needed controller, as well as the initial indexAction.
  6. Open the database configuration in the Frontend module, blog/apps/frontend/config/config.php, and edit the database configuration according to your current environment. Enter the name of an existing database user and a password that has access to that database, and the application database name. You can also change the database adapter that your application needs. If you do not have a database ready, you can create one now.
  7. Now, after you have configured the database access, let’s create a users table in your database. Create the users table and fill it with the primary data:
    CREATE TABLE `users` (
      `id` INT(11) unsigned NOT NULL AUTO_INCREMENT,
      `email` VARCHAR(128) NOT NULL,
      `first_name` VARCHAR(64) DEFAULT NULL,
      `last_name` VARCHAR(64) DEFAULT NULL,
      `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      UNIQUE KEY `users_email` (`email`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    INSERT INTO `users` (`email`, `first_name`, `last_name`) VALUES
    ('[email protected]', 'John', 'Doe'),
    ('[email protected]', 'Janie', 'Doe');
  8. Next, let’s create Controller, Views, Layout, and Model by using the scaffold command:
    phalcon scaffold users --ns-
    controllers=Blog\Frontend\Controllers —ns-
    models=Blog\Frontend\Models
  9. Open the newly generated UsersController located in the apps/frontend/controllers/UsersController.php file to ensure you have generated all actions needed for user search, editing, creating, displaying, and deleting.
  10. To check if all actions work as designed, if you have a web server installed and configured for this recipe, you can go to http://{your-server}/users/index. In so doing, you can make sure that the required Users model is created in the apps/frontend/models/Users.php file, all the required views are created in the apps/frontend/views/users folder, and the user layout is created in the apps/frontend/views/layouts folder.
  11. If you have a web server installed and configured for displaying the newly created site, go to http://{your-server}/users/search to ensure that the users from our table are shown.

How it works…

In the world of programming, code generation is designed to lessen the burden of manually creating repeated code by using predefined code templates. The Phalcon framework provides perfect code generation tools which come with Phalcon Developer Tools.

We start with the installation of Phalcon Developer Tools. Note, that if you already have Developer Tools installed, you should skip the steps involving these installation.

Next, we generate a fully functional MVC application, which implements the multi-module principle. One command is enough to get a working application at once. We save ourselves the trouble of creating the application directory structure, creating the bootstrap file, creating all the required files, and setting up the initial application structure. For that end, we use only one command. It’s really great, isn’t it?

Our next step is creating a controller. In our example, we use HelpController, which displays just such an approach to creating controllers.

Next, we create the table users in our database and fill it with data. With that done, we use a powerful tool for generating predefined code templates, which is called Scaffold. Using only one command in the Terminal, we generate the controller UsersController with all the necessary actions and appropriate views. Besides this, we get the Users model and required layout.

If you have a web server configured you can check out the work of Developer Tools at http://{your-server}/users/index.

When we use the Scaffold command, the generator determines the presence and names of our table fields. Based on these data, the tool generates a model, as well as views with the required fields. The generator provides you with ready-to-use code in the controller, and you can change this code according to your needs. However, even if you don’t change anything, you can use your controller safely. You can search for users, edit and delete them, create new users, and view them. And all of this was made possible with one command.

We have discussed only some of the features of code generation. Actually, Phalcon Developer Tools has many more features. For help on the available commands you can use the command phalcon (without arguments).

There’s more…

For more detailed information on installation and configuration of PDO in PHP, visit http://php.net/manual/en/pdo.installation.php. You can find detailed Phalcon Developer Tools installation instructions at https://docs.phalconphp.com/en/latest/reference/tools.html. For more information on Scaffold, refer to https://en.wikipedia.org/wiki/Scaffold_(programming).

Summary

In this article, you learned about the automation of routine tasks andcreating the application structure.

Resources for Article:


Further resources on this subject:


LEAVE A REPLY

Please enter your comment!
Please enter your name here