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.)
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.
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.
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.
Follow these steps to complete this recipe:
<?php
namespace Library;
use PhalconMvcUserComponent;
use PhalconMvcViewSimple as View;
class Elements extends Component
{
public function __construct()
{
// ...
}
public function getMenu()
{
// ...
}
}
$di->setShared('elements', function () {
return new LibraryElements();
});
$di->setShared('session', function () {
$session = new PhalconSessionAdapterFiles();
$session->start();
return $session;
});
$loader->registerNamespaces([
// The APP_PATH constant should point
// to the project's root
'Library' => APP_PATH . '/apps/library/',
// ...
]);
<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>
<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>
public function __construct()
{
$this->simpleView = new View();
$this->simpleView->setDI($this->getDI());
}
public function getMenu()
{
$this->simpleView->setViewsDir($this->view-
>getViewsDir());
return $this->simpleView->render('templates/topMenu');
}
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.
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.
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.
Follow these steps to complete this recipe:
git clone git@github.com:phalcon/phalcon-devtools.git devtools
$ ./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!
$ 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)
$ phalcon project myapp simple
mysql -e 'CREATE DATABASE myapp' -u root -p
<?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/',
]
]);
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
('john@doe.com', 'John', 'Doe'),
('janie@doe.com', 'Janie', 'Doe');
$ phalcon scaffold users
+-- app
¦ +-- cache
¦ +-- config
¦ +-- controllers
¦ +-- library
¦ +-- migrations
¦ +-- models
¦ +-- plugins
¦ +-- schemas
¦ +-- views
¦ +-- index
¦ +-- layouts
¦ +-- users
+-- public
+-- css
+-- files
+-- img
+-- js
+-- temp
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.
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
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.
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.
Follow these steps to complete this recipe:
git clone git@github.com:phalcon/phalcon-devtools.git
./phalcon.sh
phalcon project blog modules
phalcon controller Help --base-class=ControllerBase —
namespace=Blog\Frontend\Controllers
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
('john@doe.com', 'John', 'Doe'),
('janie@doe.com', 'Janie', 'Doe');
phalcon scaffold users --ns-
controllers=Blog\Frontend\Controllers —ns-
models=Blog\Frontend\Models
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).
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).
In this article, you learned about the automation of routine tasks andcreating the application structure.
Further resources on this subject: