Phalcon Devtools


DevTools - 图1

Overview

These tools are a collection of useful scripts to generate skeleton code. Core components of your application can be generated with a simple command, allowing you to easily develop applications using Phalcon.

If you prefer to use the web version instead of the console, this blog post offers more information.

Installation

Linux

These steps will guide you through the process of installing Phalcon Developer Tools for Linux. The Phalcon PHP extension is required to run Phalcon Tools. If you haven’t installed it yet, please see the Installation section for instructions. You can download a cross platform package containing the developer tools from from GitHub. Open a terminal and type the command below:

  1. git clone git://github.com/phalcon/phalcon-devtools.git

DevTools - 图2

Then enter the folder where the tools were cloned and execute . ./phalcon.sh, (don’t forget the dot at beginning of the command):

  1. cd phalcon-devtools/
  2. . ./phalcon.sh

DevTools - 图3

Create a symbolic link to the phalcon.php script:

  1. ln -s ~/phalcon-devtools/phalcon.php /usr/bin/phalcon
  2. chmod ugo+x /usr/bin/phalcon

macOS

Open a terminal and type the command below:

  1. git clone git://github.com/phalcon/phalcon-devtools.git

DevTools - 图4

Then enter the folder where the tools were cloned and execute . ./phalcon.sh, (don’t forget the dot at beginning of the command):

  1. cd phalcon-devtools/
  2. . ./phalcon.sh

DevTools - 图5

Next, we’ll create a symbolic link to the phalcon.php script. On El Capitan and newer versions of macOS:

  1. ln -s ~/phalcon-devtools/phalcon.php /usr/local/bin/phalcon
  2. chmod ugo+x /usr/local/bin/phalcon

if you are running an older version:

  1. ln -s ~/phalcon-devtools/phalcon.php /usr/bin/phalcon
  2. chmod ugo+x /usr/bin/phalcon

Windows

On the Windows platform, you need to configure the system PATH to include Phalcon tools as well as the PHP executable. If you download the Phalcon tools as a zip archive, extract it on any path of your local drive i.e. c:\phalcon-tools. You will need this path in the steps below. Edit the file phalcon.bat by right clicking on the file and selecting Edit:

DevTools - 图6

Change the path to the one you installed the Phalcon tools (set PTOOLSPATH=C:\phalcon-tools\):

DevTools - 图7

Save the changes.

Adding PHP and Tools to your system PATH

Because the scripts are written in PHP, you need to install it on your machine. Depending on your PHP installation, the executable can be located in various places. Search for the file php.exe and copy its path. For instance, using WAMPP you will locate the PHP executable in a location like this: C:\wamp\bin\php\<php version>\php.exe (where <php version> is the version of PHP that WAMPP comes bundled with).

From the Windows start menu, right mouse click on the Computer icon and select Properties:

DevTools - 图8

Click the Advanced tab and then the button Environment Variables:

DevTools - 图9

At the bottom, look for the section System variables and edit the variable Path:

DevTools - 图10

Be very careful on this step! You need to append at the end of the long string the path where your php.exe was located and the path where Phalcon tools are installed. Use the ; character to separate the different paths in the variable:

DevTools - 图11

Accept the changes made by clicking OK and close the dialogs opened. From the start menu click on the option Run. If you can’t find this option, press Windows Key + R.

DevTools - 图12

Type cmd and press enter to open the windows command line utility:

DevTools - 图13

Type the commands php -v and phalcon and you will see something like this:

DevTools - 图14

Congratulations you now have Phalcon tools installed!

Usage

Available Commands

You can get a list of available commands in Phalcon tools by typing: phalcon commands

  1. $ phalcon commands
  2. Phalcon DevTools (3.0.0)
  3. Available commands:
  4. commands (alias of: list, enumerate)
  5. controller (alias of: create-controller)
  6. module (alias of: create-module)
  7. model (alias of: create-model)
  8. all-models (alias of: create-all-models)
  9. project (alias of: create-project)
  10. scaffold (alias of: create-scaffold)
  11. migration (alias of: create-migration)
  12. webtools (alias of: create-webtools)

Generating a Project Skeleton

You can use Phalcon tools to generate pre-defined project skeletons for your applications with Phalcon framework. By default the project skeleton generator will use mod_rewrite for Apache. Type the following command on your web server document root:

  1. $ pwd
  2. /Applications/MAMP/htdocs
  3. $ phalcon create-project store

The above recommended project structure was generated:

DevTools - 图15

You could add the parameter —help to get help on the usage of a certain script:

  1. $ phalcon project --help
  2. Phalcon DevTools (3.0.0)
  3. Help:
  4. Creates a project
  5. Usage:
  6. project [name] [type] [directory] [enable-webtools]
  7. Arguments:
  8. help Shows this help text
  9. Example
  10. phalcon project store simple
  11. Options:
  12. --name Name of the new project
  13. --enable-webtools Determines if webtools should be enabled [optional]
  14. --directory=s Base path on which project will be created [optional]
  15. --type=s Type of the application to be generated (cli, micro, simple, modules)
  16. --template-path=s Specify a template path [optional]
  17. --use-config-ini Use a ini file as configuration file [optional]
  18. --trace Shows the trace of the framework in case of exception. [optional]
  19. --help Shows this help

Accessing the project from the web server will show you:

DevTools - 图16

Generating Controllers

The command create-controller generates controller skeleton structures. It’s important to invoke this command inside a directory that already has a Phalcon project.

  1. $ phalcon create-controller --name test

The following code is generated by the script:

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

Preparing Database Settings

When a project is generated using developer tools. A configuration file can be found in app/config/config.php. To generate models or scaffold, you will need to change the settings used to connect to your database.

Change the database section in your config.php file:

  1. <?php
  2. defined('BASE_PATH') || define('BASE_PATH', getenv('BASE_PATH') ?: realpath(dirname(__FILE__) . '/../..'));
  3. defined('APP_PATH') || define('APP_PATH', BASE_PATH . '/app');
  4. return new \Phalcon\Config(
  5. [
  6. 'database' => [
  7. 'adapter' => 'Mysql',
  8. 'host' => 'localhost',
  9. 'username' => 'root',
  10. 'password' => 'secret',
  11. 'dbname' => 'test',
  12. 'charset' => 'utf8',
  13. ],
  14. 'application' => [
  15. 'appDir' => APP_PATH . '/',
  16. 'controllersDir' => APP_PATH . '/controllers/',
  17. 'modelsDir' => APP_PATH . '/models/',
  18. 'migrationsDir' => APP_PATH . '/migrations/',
  19. 'viewsDir' => APP_PATH . '/views/',
  20. 'pluginsDir' => APP_PATH . '/plugins/',
  21. 'libraryDir' => APP_PATH . '/library/',
  22. 'cacheDir' => BASE_PATH . '/cache/',
  23. // This allows the baseUri to be understand project paths that are not in the root directory
  24. // of the webpspace. This will break if the public/index.php entry point is moved or
  25. // possibly if the web server rewrite rules are changed. This can also be set to a static path.
  26. 'baseUri' => preg_replace(
  27. '/public([\/\\])index.php$/',
  28. '',
  29. $_SERVER["PHP_SELF"]
  30. ),
  31. ],
  32. ]
  33. );

Generating Models

There are several ways to create models. You can create all models from the default database connection or some selectively. Models can have public attributes for the field representations or setters/getters can be used.

  1. Options:
  2. --name=s Table name
  3. --schema=s Name of the schema. [optional]
  4. --namespace=s Model's namespace [optional]
  5. --get-set Attributes will be protected and have setters/getters. [optional]
  6. --extends=s Model extends the class name supplied [optional]
  7. --excludefields=l Excludes fields defined in a comma separated list [optional]
  8. --doc Helps to improve code completion on IDEs [optional]
  9. --directory=s Base path on which project will be created [optional]
  10. --force Rewrite the model. [optional]
  11. --trace Shows the trace of the framework in case of exception. [optional]
  12. --mapcolumn Get some code for map columns. [optional]
  13. --abstract Abstract Model [optional]

The simplest way to generate a model is:

  1. $ phalcon model products
  1. $ phalcon model --name tablename

All table fields are declared public for direct access.

  1. <?php
  2. use Phalcon\Mvc\Model;
  3. class Products extends Model
  4. {
  5. /**
  6. * @var integer
  7. */
  8. public $id;
  9. /**
  10. * @var integer
  11. */
  12. public $typesId;
  13. /**
  14. * @var string
  15. */
  16. public $name;
  17. /**
  18. * @var string
  19. */
  20. public $price;
  21. /**
  22. * @var integer
  23. */
  24. public $quantity;
  25. /**
  26. * @var string
  27. */
  28. public $status;
  29. }

By adding the —get-set you can generate the fields with protected variables and public setter/getter methods. Those methods can help in business logic implementation within the setter/getter methods.

  1. <?php
  2. use Phalcon\Mvc\Model;
  3. class Products extends Model
  4. {
  5. /**
  6. * @var integer
  7. */
  8. protected $id;
  9. /**
  10. * @var integer
  11. */
  12. protected $typesId;
  13. /**
  14. * @var string
  15. */
  16. protected $name;
  17. /**
  18. * @var string
  19. */
  20. protected $price;
  21. /**
  22. * @var integer
  23. */
  24. protected $quantity;
  25. /**
  26. * @var string
  27. */
  28. protected $status;
  29. /**
  30. * Method to set the value of field id
  31. *
  32. * @param integer $id
  33. */
  34. public function setId($id)
  35. {
  36. $this->id = $id;
  37. }
  38. /**
  39. * Method to set the value of field typesId
  40. *
  41. * @param integer $typesId
  42. */
  43. public function setTypesId($typesId)
  44. {
  45. $this->typesId = $typesId;
  46. }
  47. // ...
  48. /**
  49. * Returns the value of field status
  50. *
  51. * @return string
  52. */
  53. public function getStatus()
  54. {
  55. return $this->status;
  56. }
  57. }

A nice feature of the model generator is that it keeps changes made by the developer between code generations. This allows the addition or removal of fields and properties, without worrying about losing changes made to the model itself. The following screencast shows you how it works:

Scaffold a CRUD

Scaffolding is a quick way to generate some of the major pieces of an application. If you want to create the models, views, and controllers for a new resource in a single operation, scaffolding is the tool for the job.

Once the code is generated, it will have to be customized to meet your needs. Many developers avoid scaffolding entirely, opting to write all or most of their source code from scratch. The generated code can serve as a guide to better understand of how the framework works or develop prototypes. The code below shows a scaffold based on the table products:

  1. $ phalcon scaffold --table-name products

The scaffold generator will build several files in your application, along with some folders. Here’s a quick overview of what will be generated:

FilePurpose
app/controllers/ProductsController.phpThe Products controller
app/models/Products.phpThe Products model
app/views/layout/products.phtmlController layout for Products
app/views/products/new.phtmlView for the action new
app/views/products/edit.phtmlView for the action edit
app/views/products/search.phtmlView for the action search

When browsing the recently generated controller, you will see a search form and a link to create a new Product:

DevTools - 图17

The create page allows you to create products applying validations on the Products model. Phalcon will automatically validate not null fields producing warnings if any of them is required.

DevTools - 图18

After performing a search, a pager component is available to show paged results. Use the “Edit” or “Delete” links in front of each result to perform such actions.

DevTools - 图19

Web Interface to Tools

Also, if you prefer, it’s possible to use Phalcon Developer Tools from a web interface. Check out the following screencast to figure out how it works:

Integrating Tools with PhpStorm IDE

The screencast below shows how to integrate developer tools with the PhpStorm IDE. The configuration steps could be easily adapted to other IDEs for PHP.