Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Learning Phalcon PHP
Learning Phalcon PHP

Learning Phalcon PHP: Learn Phalcon interactively and build high-performance web applications

eBook
$39.59 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Learning Phalcon PHP

Chapter 2. Setting Up the MVC Structure and the Environment for Our Project

In the previous chapter, we summarized the most common parts of Phalcon. Next, we will try to set up the "Hello world" page for our project. In this chapter, we will cover these topics:

  • An introduction to MVC—what is MVC?
  • The MVC structure
  • Creating a configuration file and the Bootstrap
  • Preparing the initial DI interface and the router
  • Using the router component in a module
  • Creating the base layout

What is MVC?

I am pretty sure that if you are reading this book, you are already familiar with the MVC pattern, but for beginners, we will try to explain this in a few words.

MVC is defined as an architectural pattern, and it stands for Model-View-Controller; it is used mostly in web development, but it is widely applied in software that needs a Graphical User Interface (GUI). To make this introduction quick, let's explain these components:

  • Model: This is usually used as an abstraction layer, and validation for the tables of a database, but it can be used to handle any kind of logic within the application.
  • View: A view, usually, represents a template (can be an HTML file) that the controller will render.
  • Controller: In a web application, the controller handles all the HTTP requests and sends an appropriate response. This response can mean rendering a template, outputting JSON data, and so on.

Note

For the exact definition, I suggest you check out the Wikipedia page of the MVC pattern at...

The MVC structure

This subject (like many other subjects) is quite sensitive. It depends on how much experience you have and how you are used to structure your projects. In a web application, most of the time we have models, views (templates), controllers, and assets (images, JavaScript files, and style sheets). Based on this, I like the following structure, because it's easy to understand where a file resides and what its purpose is.

For a single module application, we can have the following structure:

The MVC structure

For a multi-module application, we can have the following structure:

The MVC structure

As you can see, it is quite easy to know exactly what a file is used for and where we can find it. In the end, you should choose the structure that fits your needs but keep in mind that if you are going to work in a team, it should be intuitive enough for any new member.

Creating the structure for our project

Now, we are going to create the structure for our project. In the first chapter, we created the /var/www/learning-phalcon.localhost folder. If you have another location, go there and create the following directory structure:

Creating the structure for our project

Next, let's create the index.php file that will handle our application. This file will be the default file in our web server:

<?php

header('Content-Type: text/html; charset=utf-8');
mb_internal_encoding("UTF-8");

require_once __DIR__.'/../modules/Bootstrap.php';

$app = new Bootstrap('frontend');
$app->init();
?>

In the first two lines, we set the header and internal encoding to UTF-8. This is a good practice if you are going to use special characters / diacritics. In the fourth line, we include a file named Bootstrap.php. This file is the Bootstrap of our project, and we will create its content in a few moments. On the next lines, we create a new instance of Bootstrap with a...

Creating the configuration file and the Bootstrap

Almost any application has some constants that will be reused (database credentials, SMTP credentials, and so on). For our application, we will create a global configuration file. This file will be an instance of the \Phalcon\Config component. Switch to the config directory and create it with the following content:

<?php

return new \Phalcon\Config(array(
    'application' => array(
        'name' => 'Learning Phalcon'
    ),
    'root_dir' => __DIR__.'/../',
    'redis' => array(
        'host' => '127.0.0.1',
        'port' => 6379,
    ),
    'session' => array(
        'unique_id' => 'learning_phalcon',
        'name' => 'learning_phalcon',
        'path' => 'tcp://127.0.0.1:6379?weight=1'
    ),
    'view' => array(
        'cache...

Preparing the initial DI interface and the router

In the Bootstrap, we don't have two files: services.php and routing.php. The services.php file will hold the information about global services that our application will use, and the routing.php file will hold information about our routes. Let's start by creating the services.php file in our config folder with the following content:

<?php
use \Phalcon\Logger\Adapter\File as Logger;

$di['session'] = function () use ($config) {

    $session = new \Phalcon\Session\Adapter\Redis(array(
        'uniqueId' => $config->session->unique_id,
        'path' => $config->session->path,
        'name' => $config->session->name
    ));

    $session->start();

    return $session;
};

$di['security'] = function () {
    $security = new \Phalcon\Security();
    $security->setWorkFactor(10);

    return $security;
};

$di['redis'] = function () use ...

What is MVC?


I am pretty sure that if you are reading this book, you are already familiar with the MVC pattern, but for beginners, we will try to explain this in a few words.

MVC is defined as an architectural pattern, and it stands for Model-View-Controller; it is used mostly in web development, but it is widely applied in software that needs a Graphical User Interface (GUI). To make this introduction quick, let's explain these components:

  • Model: This is usually used as an abstraction layer, and validation for the tables of a database, but it can be used to handle any kind of logic within the application.

  • View: A view, usually, represents a template (can be an HTML file) that the controller will render.

  • Controller: In a web application, the controller handles all the HTTP requests and sends an appropriate response. This response can mean rendering a template, outputting JSON data, and so on.

Note

For the exact definition, I suggest you check out the Wikipedia page of the MVC pattern at http...

The MVC structure


This subject (like many other subjects) is quite sensitive. It depends on how much experience you have and how you are used to structure your projects. In a web application, most of the time we have models, views (templates), controllers, and assets (images, JavaScript files, and style sheets). Based on this, I like the following structure, because it's easy to understand where a file resides and what its purpose is.

For a single module application, we can have the following structure:

For a multi-module application, we can have the following structure:

As you can see, it is quite easy to know exactly what a file is used for and where we can find it. In the end, you should choose the structure that fits your needs but keep in mind that if you are going to work in a team, it should be intuitive enough for any new member.

Creating the structure for our project


Now, we are going to create the structure for our project. In the first chapter, we created the /var/www/learning-phalcon.localhost folder. If you have another location, go there and create the following directory structure:

Next, let's create the index.php file that will handle our application. This file will be the default file in our web server:

<?php

header('Content-Type: text/html; charset=utf-8');
mb_internal_encoding("UTF-8");

require_once __DIR__.'/../modules/Bootstrap.php';

$app = new Bootstrap('frontend');
$app->init();
?>

In the first two lines, we set the header and internal encoding to UTF-8. This is a good practice if you are going to use special characters / diacritics. In the fourth line, we include a file named Bootstrap.php. This file is the Bootstrap of our project, and we will create its content in a few moments. On the next lines, we create a new instance of Bootstrap with a default module (frontend), and we initialize...

Left arrow icon Right arrow icon

Description

Phalcon is a full-stack PHP framework implemented as a C extension. Building applications with Phalcon will offer you lower resource consumption and high performance whether your application runs on a Linux machine or a Windows one. Phalcon is loosely coupled, allowing you to use its objects as glue components based on the needs of your application. Phalcon PHP's mission is to give you an advanced tool to develop faster websites and applications. This book covers the most common and useful parts of PhalconPHP, which will guide you to make the right decisions while developing a Phalcon-driven application. You will begin the journey by installing and setting up Phalcon for your environment followed by the development of each module. You will be introduced to Phalcon's ORM and ODM. Furthermore, you will also be able to create the first models and database architecture for your project. You will then cover command-line applications, API module, volt syntax, and hierarchical views. Installing and working with Node and Bower for assets management will also be covered. Finally, you will gain insights into creating the backoffice and frontend module along with best practices and resources for development with Phalcon PHP. By the end of this book, you will be able to confidently develop any kind of application using the Phalcon PHP framework in a short time.

Who is this book for?

If you are a web developer and want to build effective web applications with Phalcon PHP, then this book is ideal for you. The book does not assume detailed knowledge of PHP frameworks.

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 26, 2015
Length: 328 pages
Edition : 1st
Language : English
ISBN-13 : 9781783555109
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Aug 26, 2015
Length: 328 pages
Edition : 1st
Language : English
ISBN-13 : 9781783555109
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 98.98
Phalcon Cookbook
$43.99
Learning Phalcon PHP
$54.99
Total $ 98.98 Stars icon

Table of Contents

11 Chapters
1. Getting Started with Phalcon Chevron down icon Chevron up icon
2. Setting Up the MVC Structure and the Environment for Our Project Chevron down icon Chevron up icon
3. Learning Phalcon's ORM and ODM Chevron down icon Chevron up icon
4. Database Architecture, Models, and CLI Applications Chevron down icon Chevron up icon
5. The API Module Chevron down icon Chevron up icon
6. Assets, Authentication, and ACL Chevron down icon Chevron up icon
7. The Backoffice Module (Part 1) Chevron down icon Chevron up icon
8. The Backoffice Module (Part 2) Chevron down icon Chevron up icon
9. The Frontend Module Chevron down icon Chevron up icon
10. Going Further Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.

Modal Close icon
Modal Close icon