Tutorial - basic

Throughout this tutorial, we’ll walk you through the creation of an application with a simple registration form from the ground up. The following guide is to provided to introduce you to Phalcon framework’s design aspects.

This tutorial covers the implementation of a simple MVC application, showing how fast and easy it can be done with Phalcon. This tutorial will get you started and help create an application that you can extend to address many needs. The code in this tutorial can also be used as a playground to learn other Phalcon specific concepts and ideas.

If you just want to get started you can skip this and create a Phalcon project automatically with our developer tools. (It is recommended that if you have not had experience with to come back here if you get stuck)

The best way to use this guide is to follow along and try to have fun. You can get the complete code here. If you get hung-up on something please visit us on Discord or in our Forum.

File structure

A key feature of Phalcon is it’s loosely coupled, you can build a Phalcon project with a directory structure that is convenient for your specific application. That said some uniformity is helpful when collaborating with others, so this tutorial will use a “Standard” structure where you should feel at home if you have worked with other MVC’s in the past.

  1. .
  2. └── tutorial
  3. ├── app
  4. ├── controllers
  5. ├── IndexController.php
  6. └── SignupController.php
  7. ├── models
  8. └── Users.php
  9. └── views
  10. └── public
  11. ├── css
  12. ├── img
  13. ├── index.php
  14. └── js

Note: You will not see a vendor directory as all of Phalcon's core dependencies are loaded into memory via the Phalcon extension you should have installed. If you missed that part have not installed the Phalcon extension please go back and finish the installation before continuing.

If this is all brand new it is recommended that you install the Phalcon Devtools since it leverages PHP’s built-in server you to get your app running without having to configure a web server by adding this .htrouter to the root of your project.

Otherwise if you want to use Nginx here are some additional setup here.

Apache can also be used with these additional setup here.

Finally, if you flavor is Cherokee use the setup here.

Bootstrap

The first file you need to create is the bootstrap file. This file acts as the entry-point and configuration for your application. In this file, you can implement initialization of components as well as application behavior.

This file handles 3 things:

  • Registration of component autoloaders
  • Configuring Services and registering them with the Dependency Injection context
  • Resolving the application’s HTTP requests

Autoloaders

Autoloaders leverage a PSR-4 compliant file loader running through the Phalcon. Common things that should be added to the autoloader are your controllers and models. You can register directories which will search for files within the application’s namespace. If you want to read about other ways that you can use autoloaders head here.

To start, lets register our app’s controllers and models directories.Don’t forget to include the loader from Phalcon\Loader.

public/index.php

  1. <?php
  2. use Phalcon\Loader;
  3. // Define some absolute path constants to aid in locating resources
  4. define('BASE_PATH', dirname(__DIR__));
  5. define('APP_PATH', BASE_PATH . '/app');
  6. // ...
  7. $loader = new Loader();
  8. $loader->registerDirs(
  9. [
  10. APP_PATH . '/controllers/',
  11. APP_PATH . '/models/',
  12. ]
  13. );
  14. $loader->register();

Dependency Management

Since Phalcon is loosely coupled, services are registered with the frameworks Dependency Manager so they can be injected automatically to components and services wrapped in the IoC container. Frequently you will encounter the term DI which stands for Dependency Injection. Dependency Injection and Inversion of Control(IoC) may sound like a complex feature but in Phalcon their use is very simple and practical. Phalcon’s IoC container consists of the following concepts:

  • Service Container: a “bag” where we globally store the services that our application needs to function.
  • Service or Component: Data processing object which will be injected into components
    Each time the framework requires a component or service, it will ask the container using an agreed upon name for the service. Don’t forget to include Phalcon\Di with setting up the service container.

If you are still interested in the details please see this article by Martin Fowler. Also we have a great tutorial covering many use cases.

Factory Default

The Phalcon\Di\FactoryDefault is a variant of Phalcon\Di. To make things easier, it will automatically register most of the components that come with Phalcon. We recommend that you register your services manually but this has been included to help lower the barrier of entry when getting used to Dependency Management. Later, you can always specify once you become more comfortable with the concept.

Services can be registered in several ways, but for our tutorial, we’ll use an anonymous function:

public/index.php

  1. <?php
  2. use Phalcon\Di\FactoryDefault;
  3. // ...
  4. // Create a DI
  5. $di = new FactoryDefault();

In the next part, we register the “view” service indicating the directory where the framework will find the views files. As the views do not correspond to classes, they cannot be charged with an autoloader.

public/index.php

  1. <?php
  2. use Phalcon\Mvc\View;
  3. // ...
  4. // Setup the view component
  5. $di->set(
  6. 'view',
  7. function () {
  8. $view = new View();
  9. $view->setViewsDir(APP_PATH . '/views/');
  10. return $view;
  11. }
  12. );

Next, we register a base URI so that all URIs generated by Phalcon match the application’s base path of “/”. This will become important later on in this tutorial when we use the class Phalcon\Tag to generate a hyperlink.

public/index.php

  1. <?php
  2. use Phalcon\Mvc\Url as UrlProvider;
  3. // ...
  4. // Setup a base URI
  5. $di->set(
  6. 'url',
  7. function () {
  8. $url = new UrlProvider();
  9. $url->setBaseUri('/');
  10. return $url;
  11. }
  12. );

Handling the application request

In the last part of this file, we find Phalcon\Mvc\Application. Its purpose is to initialize the request environment, route the incoming request, and then dispatch any discovered actions; it aggregates any responses and returns them when the process is complete.

public/index.php

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

Putting everything together

The tutorial/public/index.php file should look like:

public/index.php

  1. <?php
  2. use Phalcon\Loader;
  3. use Phalcon\Mvc\View;
  4. use Phalcon\Mvc\Application;
  5. use Phalcon\Di\FactoryDefault;
  6. use Phalcon\Mvc\Url as UrlProvider;
  7. // Define some absolute path constants to aid in locating resources
  8. define('BASE_PATH', dirname(__DIR__));
  9. define('APP_PATH', BASE_PATH . '/app');
  10. // Register an autoloader
  11. $loader = new Loader();
  12. $loader->registerDirs(
  13. [
  14. APP_PATH . '/controllers/',
  15. APP_PATH . '/models/',
  16. ]
  17. );
  18. $loader->register();
  19. // Create a DI
  20. $di = new FactoryDefault();
  21. // Setup the view component
  22. $di->set(
  23. 'view',
  24. function () {
  25. $view = new View();
  26. $view->setViewsDir(APP_PATH . '/views/');
  27. return $view;
  28. }
  29. );
  30. // Setup a base URI
  31. $di->set(
  32. 'url',
  33. function () {
  34. $url = new UrlProvider();
  35. $url->setBaseUri('/');
  36. return $url;
  37. }
  38. );
  39. $application = new Application($di);
  40. try {
  41. // Handle the request
  42. $response = $application->handle();
  43. $response->send();
  44. } catch (\Exception $e) {
  45. echo 'Exception: ', $e->getMessage();
  46. }

As you can see, the bootstrap file is very short and we do not need to include any additional files. Congratulations you are well on your to having created a flexible MVC application in less than 30 lines of code.

Creating a Controller

By default Phalcon will look for a controller named IndexController. It is the starting point when no controller or action has been added in the request (eg. http://localhost:8000/). An IndexController and its IndexAction should resemble the following example:

app/controllers/IndexController.php

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class IndexController extends Controller
  4. {
  5. public function indexAction()
  6. {
  7. echo '<h1>Hello!</h1>';
  8. }
  9. }

The controller classes must have the suffix Controller and controller actions must have the suffix Action. If you access the application from your browser, you should see something like this:

Basic - 图1

Congratulations, you’re phlying with Phalcon!

Sending output to a view

Sending output to the screen from the controller is at times necessary but not desirable as most purists in the MVC community will attest. Everything must be passed to the view that is responsible for outputting data on screen. Phalcon will look for a view with the same name as the last executed action inside a directory named as the last executed controller. In our case (app/views/index/index.phtml):

app/views/index/index.phtml

  1. <?php echo "<h1>Hello!</h1>";

Our controller (app/controllers/IndexController.php) now has an empty action definition:

app/controllers/IndexController.php

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

The browser output should remain the same. The Phalcon\Mvc\View static component is automatically created when the action execution has ended. Learn more about views usage here.

Designing a sign-up form

Now we will change the index.phtml view file, to add a link to a new controller named “signup”. The goal is to allow users to sign up within our application.

app/views/index/index.phtml

  1. <?php
  2. echo "<h1>Hello!</h1>";
  3. echo PHP_EOL;
  4. echo PHP_EOL;
  5. echo $this->tag->linkTo(
  6. 'signup',
  7. 'Sign Up Here!'
  8. );

The generated HTML code displays an anchor (<a>) HTML tag linking to a new controller:

app/views/index/index.phtml (rendered)

  1. <h1>Hello!</h1>
  2. <a href="/signup">Sign Up Here!</a>

To generate the tag we use the class Phalcon\Tag. This is a utility class that allows us to build HTML tags with framework conventions in mind. As this class is also a service registered in the DI we use $this->tag to access it.

A more detailed article regarding HTML generation can be found here.

Basic - 图2

Here is the Signup controller (app/controllers/SignupController.php):

app/controllers/SignupController.php

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

The empty index action gives the clean pass to a view with the form definition (app/views/signup/index.phtml):

app/views/signup/index.phtml

  1. <h2>Sign up using this form</h2>
  2. <?php echo $this->tag->form("signup/register"); ?>
  3. <p>
  4. <label for="name">Name</label>
  5. <?php echo $this->tag->textField("name"); ?>
  6. </p>
  7. <p>
  8. <label for="email">E-Mail</label>
  9. <?php echo $this->tag->textField("email"); ?>
  10. </p>
  11. <p>
  12. <?php echo $this->tag->submitButton("Register"); ?>
  13. </p>
  14. </form>

Viewing the form in your browser will show something like this:

Basic - 图3

Phalcon\Tag also provides useful methods to build form elements.

The Phalcon\Tag::form() method receives only one parameter for instance, a relative URI to a controller/action in the application.

By clicking the “Send” button, you will notice an exception thrown from the framework, indicating that we are missing the register action in the controller signup. Our public/index.php file throws this exception:

  1. Exception: Action "register" was not found on handler "signup"

Implementing that method will remove the exception:

app/controllers/SignupController.php

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

If you click the “Send” button again, you will see a blank page. The name and email input provided by the user should be stored in a database. According to MVC guidelines, database interactions must be done through models so as to ensure clean object-oriented code.

Creating a Model

Phalcon brings the first ORM for PHP entirely written in C-language. Instead of increasing the complexity of development, it simplifies it.

Before creating our first model, we need to create a database table outside of Phalcon to map it to. A simple table to store registered users can be created like this:

create_users_table.sql

  1. CREATE TABLE `users` (
  2. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  3. `name` varchar(70) NOT NULL,
  4. `email` varchar(70) NOT NULL,
  5. PRIMARY KEY (`id`)
  6. );

A model should be located in the app/models directory (app/models/Users.php). The model maps to the “users” table:

app/models/Users.php

  1. <?php
  2. use Phalcon\Mvc\Model;
  3. class Users extends Model
  4. {
  5. public $id;
  6. public $name;
  7. public $email;
  8. }

Setting a Database Connection

In order to use a database connection and subsequently access data through our models, we need to specify it in our bootstrap process. A database connection is just another service that our application has that can be used for several components:

public/index.php

  1. <?php
  2. use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
  3. // Setup the database service
  4. $di->set(
  5. 'db',
  6. function () {
  7. return new DbAdapter(
  8. [
  9. 'host' => '127.0.0.1',
  10. 'username' => 'root',
  11. 'password' => 'secret',
  12. 'dbname' => 'tutorial1',
  13. ]
  14. );
  15. }
  16. );

With the correct database parameters, our models are ready to work and interact with the rest of the application.

Storing data using models

app/controllers/SignupController.php

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class SignupController extends Controller
  4. {
  5. public function indexAction()
  6. {
  7. }
  8. public function registerAction()
  9. {
  10. $user = new Users();
  11. // Store and check for errors
  12. $success = $user->save(
  13. $this->request->getPost(),
  14. [
  15. "name",
  16. "email",
  17. ]
  18. );
  19. if ($success) {
  20. echo "Thanks for registering!";
  21. } else {
  22. echo "Sorry, the following problems were generated: ";
  23. $messages = $user->getMessages();
  24. foreach ($messages as $message) {
  25. echo $message->getMessage(), "<br/>";
  26. }
  27. }
  28. $this->view->disable();
  29. }
  30. }

At the beginning of the registerAction we create an empty user object from the Users class, which manages a User’s record. The class’s public properties map to the fields of the users table in our database. Setting the relevant values in the new record and calling save() will store the data in the database for that record. The save() method returns a boolean value which indicates whether the storing of the data was successful or not.

The ORM automatically escapes the input preventing SQL injections so we only need to pass the request to the save() method.

Additional validation happens automatically on fields that are defined as not null (required). If we don’t enter any of the required fields in the sign-up form our screen will look like this:

Basic - 图4

List of users

Now let’s see how to obtain and see the users that we have registered in the database.

The first thing that we are going to do in our indexAction of the IndexController is to show the result of the search of all the users, which is done simply in the following way Users::find(). Let’s see how our indexAction would look

app/controllers/IndexController.php

  1. <?php
  2. use Phalcon\Mvc\Controller;
  3. class IndexController extends Controller
  4. {
  5. /**
  6. * Welcome and user list
  7. */
  8. public function indexAction()
  9. {
  10. $this->view->users = Users::find();
  11. }
  12. }

Now, in our view file views/index/index.phtml we will have access to the users found in the database. These will be available in the variable $users. This variable has the same name as the one we use in $this->view->users.

The view will look like this:

views/index/index.phtml

  1. <?php
  2. echo "<h1>Hello!</h1>";
  3. echo $this->tag->linkTo(["signup", "Sign Up Here!", 'class' => 'btn btn-primary']);
  4. if ($users->count() > 0) {
  5. ?>
  6. <table class="table table-bordered table-hover">
  7. <thead class="thead-light">
  8. <tr>
  9. <th>#</th>
  10. <th>Name</th>
  11. <th>Email</th>
  12. </tr>
  13. </thead>
  14. <tfoot>
  15. <tr>
  16. <td colspan="3">Users quantity: <?php echo $users->count(); ?></td>
  17. </tr>
  18. </tfoot>
  19. <tbody>
  20. <?php foreach ($users as $user) { ?>
  21. <tr>
  22. <td><?php echo $user->id; ?></td>
  23. <td><?php echo $user->name; ?></td>
  24. <td><?php echo $user->email; ?></td>
  25. </tr>
  26. <?php } ?>
  27. </tbody>
  28. </table>
  29. <?php
  30. }

As you can see our variables $users can be iterated and counted, this we will see in depth later on when viewing the models.

Basic - 图5

Adding Style

To give a design touch to our first application we will add bootstrap and a small template that will be used in all views.

We will add an index.phtml file in the views folder, with the following content:

app/views/index.phtml

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Phalcon Tutorial</title>
  6. <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
  7. </head>
  8. <body>
  9. <div class="container">
  10. <?php echo $this->getContent(); ?>
  11. </div>
  12. </body>
  13. </html>

The most important thing to highlight in our template is the function getContent() which will give us the content generated by the view. Now, our application will be something like this:

Basic - 图6

Conclusion

As you can see, it’s easy to start building an application using Phalcon. The fact that Phalcon runs from an extension significantly reduces the footprint of projects as well as giving it a considerable performance boost.

If you are ready to learn more check out the Rest Tutorial next.