Book Image

Phalcon Cookbook

By : Serghei Iakovlev, David Schissler
1 (2)
Book Image

Phalcon Cookbook

1 (2)
By: Serghei Iakovlev, David Schissler

Overview of this book

Phalcon is a high-performance PHP framework delivered as a PHP extension. This provides new opportunities for speed and application design, which until recently have been unrealized in the PHP ecosystem. Packed with simple learning exercises, technology prototypes, and real-world usable code, this book will guide you from the beginner and setup stage all the way to advanced usage. You will learn how to avoid niche pitfalls, how to use the command-line developer tools, how to integrate with new web standards, as well as how to set up and customize the MVC application structure. You will see how Phalcon can be used to quickly set up a single file web application as well as a complex multi-module application suitable for long-term projects. Some of the recipes focus on abstract concepts that are vital to get a deep comprehension of Phalcon and others are designed as a vehicle to deliver real-world usable classes and code snippets to solve advanced problems. You’ll start out with basic setup and application structure and then move onto the Phalcon MVC and routing implementation, the power of the ORM and Phalcon Query Language, and Phalcon’s own Volt templating system. Finally, you will move on to caching, security, and optimization.
Table of Contents (17 chapters)
Phalcon Cookbook
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Preface
Index

Setting up your request entry point


Before you start handling requests, you need to configure your application work environment and prepare all the required components. In this recipe, you will learn what should be done before asking Phalcon to handle an incoming request.

Getting ready

To embark on this recipe, you need to have the web server Apache or Nginx + PHP-FPM installed. Besides this, you should be able to create or change the configuration of the virtual host for your web server and have the proper authority to do so.

How to do it…

Follow these steps to complete this recipe:

  1. Create the Nginx virtual host setting as follows:

    upstream backend {
      server unix:/var/run/php5-fpm.sock;
    }
    
    # redirect the request to the non-www domain
    # to choose which domain you prefer
    server {
      server_name www.mysite.com;
      return 301 $scheme://mysite.com$request_uri;
    }
    
    server {
      listen 80;
    
      server_name mysite.com;
    
      error_log  /var/log/nginx/mysite.error.log;
      access_log /var/log/nginx/mysite.access.log;
    
      index index.php;
      root /var/www/mysite/public;
    
      try_files $uri $uri/ @rewrite;
    
      location @rewrite {
        rewrite ^(.*)$ /index.php?_url=/$1 last;
      }
    
      location ~ \.php$ {
        try_files $uri =404;
    
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
    
        fastcgi_pass backend;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
        fastcgi_param   HTTP_REFERER     $http_referer;
        # production | development | staging | testing
        fastcgi_param APP_ENV development;
        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
    
        include fastcgi_params;
      }
    
      location ~* ^/(css|img|js|flv|swf|download)/(.+)$ {
        root /var/www/mysite/public;
      }
    
      location ~ /\. {
        return 403;
      }
    }
  2. If you have the Apache web server installed, create the virtual host configuration as follows:

    <VirtualHost *:80>
      ServerAdmin [email protected]
      DocumentRoot "/var/www/mysite/public"
      DirectoryIndex index.php
      ServerName mysite.com
      ServerAlias www.mysite.com
    
      # production | development | staging | testing
      SetEnv APP_ENV development
    
      <Directory "/var/www/mysite/public">
        Options All
        AllowOverride All
        Allow from all
    
        RewriteEngine On
    
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^((?s).*)$ index.php?_url=/$1 [QSA,L]
      </Directory>
    
      <Files .*>
        Order Deny,Allow
        Deny From All
      </Files>
    </VirtualHost>
  3. Open your bootstrap file and add the URL manager configuration to it:

    $di->set('url', function () {
        $url = new \Phalcon\Mvc\Url();
        $url->setBaseUri('/');
    
        return $url;
    });
  4. Then, add the primary routing configuration:

    $di->setShared('router', function () {
      $router = new \Phalcon\Mvc\Router();
    
      if (!isset($_GET['_url'])) {
        $router->setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI);
      }
    
      $router->removeExtraSlashes(true);
    
      $router->add(
          '/',
          [
            'controller' => 'index',
            'action'     => 'index'
          ]
      );
    
      return $router;
    });
  5. Create a controller, associating it with the routing map defined in the preceding code:

    use Phalcon\Mvc\Controller;
    
    class IndexController extends Controller
    {
      public function indexAction()
      {
        var_dump($_SERVER);
        return;
      }
    }

How it works…

We configure the virtual host for our web server. Then, we configure the component Phalcon\Mvc\Url. Note that, depending on the installed application root, there may emerge a need to define the base URL. For example, if the document root is /var/www/mysite, and your application is installed at /var/www/mysite/phalcon, then your base URI (baseUri) is /phalcon/. When using virtual hosts or if the application is installed in the root directory, the baseUri parameter is /. By default, Phalcon detects the necessary baseUri by itself, but in order to improve performance we recommend to specify it manually.

For creating URIs, the Phalcon\Mvc\Router component is used by default. Your application can run with the following default routing pattern:

/:controller/:action/:params.

Therefore, it's easy to create URIs on this model or by other rules, set in the routing map. When creating an object of the type Phalcon\Mvc\Router, you can tell it not to create the default routing. For that purpose, you need to pass false to the constructor:

$router = new \Phalcon\Mvc\Router(false)

Next, we create a router with the default configuration and add a pattern to it, which refers to the site root. By default, the current handling URI is taken from the variable $_GET['_url'], Phalcon is wired that way, as are the standard mod-rewrite rules. Here we use a little trick—we check up whether there is the _url ($_GET['_url']) key in the superglobal array $_GET. In case it is missing, the virtual host configuration doesn't redirect the type index.php?_url=. Thus, it's very easy to create a flexible component configuration.

Finally, we create a controller to test our routing with an action, which coincides with the added routing pattern.

There's more…

You can learn about the Apache setup instructions at http://httpd.apache.org/docs/, and the complete Nginx documentation at http://nginx.org/en/docs/. For the PHP-FPM configuration directives description, refer to http://php.net/manual/en/install.fpm.configuration.php.

For Phalcon installation notes, routing documentation, and generating URLs, refer to https://docs.phalconphp.com/.