Learning Phalcon PHP
By Calin Rada
()
About this ebook
Learn Phalcon interactively and build high performance web applications
About This Book- Learn how to install and configure Phalcon PHP on your server
- Develop a fully functional multi-module application with Phalcon PHP
- A step-by-step guide with in-depth coverage of Phalcon and best practices
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.
What You Will Learn- Compile and install Phalcon from source code
- Set up an MVC project and learn how to use the Dependency Injection (DI), configuration, and routing
- Get to grips with Phalcon's ORM, ODM, validation and caching, and generate models using Phalcon Developer Tools
- Create a command-line application from scratch
- Write a fully functional REST module with Phalcon PHP
- Use Volt as template engine to create your first views
- Understand how session works and learn how to implement an authentication system
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.
Style and approachThis step-by-step guide will walk you through the fundamentals of Phalcon PHP. It will then help you to create a simple but fully functional news website and gain advanced knowledge of how Phalcon PHP works.
Calin Rada
Calin Rada is a full-stack developer with over 10 years of experience in web development; system architecture; database modeling; the setup, configuration, and administration of servers and hosting systems; and understanding customer and business needs. He is always interested in learning new things and working with new technologies.
Related to Learning Phalcon PHP
Related ebooks
PHPEclipse: A User Guide Rating: 3 out of 5 stars3/5Flex 3 with Java Rating: 0 out of 5 stars0 ratingsInstant StyleCop Code Analysis How-to Rating: 0 out of 5 stars0 ratingsPython for Google App Engine Rating: 0 out of 5 stars0 ratingsMeteor Design Patterns Rating: 0 out of 5 stars0 ratingsGetting Started with Meteor.js JavaScript Framework - Second Edition Rating: 0 out of 5 stars0 ratingsInstant Play Framework Starter Rating: 0 out of 5 stars0 ratingsOpenCart Theme and Module Development Rating: 0 out of 5 stars0 ratingsAdministrating Solr Rating: 0 out of 5 stars0 ratingsRedmine Plugin Extension and Development Rating: 0 out of 5 stars0 ratingsBuilding a Web Application with PHP and MariaDB: A Reference Guide Rating: 0 out of 5 stars0 ratingsBuilding Slack Bots Rating: 0 out of 5 stars0 ratingsjQuery Hotshot Rating: 0 out of 5 stars0 ratingsGetting Started with Grunt: The JavaScript Task Runner Rating: 3 out of 5 stars3/5jQuery Mobile Web Development Essentials - Third Edition Rating: 0 out of 5 stars0 ratingsResponsive Design High Performance Rating: 0 out of 5 stars0 ratingsMulti-Tier Application Programming with PHP: Practical Guide for Architects and Programmers Rating: 0 out of 5 stars0 ratingsLiving with Linux in the Industrial World Rating: 0 out of 5 stars0 ratingsHTML5 for Flash Developers Rating: 5 out of 5 stars5/5Microsoft .NET Framework 4.5 Quickstart Cookbook Rating: 0 out of 5 stars0 ratingsPHP Oracle Web Development: Data processing, Security, Caching, XML, Web Services, and Ajax Rating: 0 out of 5 stars0 ratingsModern CSS: Master the Key Concepts of CSS for Modern Web Development Rating: 0 out of 5 stars0 ratingsLearning Underscore.js Rating: 0 out of 5 stars0 ratingsYou Want to Do What with PHP? Rating: 3 out of 5 stars3/5Optimizing Visual Studio Code for Python Development: Developing More Efficient and Effective Programs in Python Rating: 0 out of 5 stars0 ratingsjQuery for Designers Beginner's Guide Second Edition Rating: 5 out of 5 stars5/5Xamarin Mobile Application Development for Android - Second Edition Rating: 0 out of 5 stars0 ratingsPro TypeScript: Application-Scale JavaScript Development Rating: 4 out of 5 stars4/5Ember.js in Action Rating: 0 out of 5 stars0 ratingsHTML5 Data and Services Cookbook Rating: 5 out of 5 stars5/5
Internet & Web For You
Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Beginner's Guide To Starting An Etsy Print-On-Demand Shop Rating: 0 out of 5 stars0 ratingsMore Porn - Faster!: 50 Tips & Tools for Faster and More Efficient Porn Browsing Rating: 3 out of 5 stars3/5The $1,000,000 Web Designer Guide: A Practical Guide for Wealth and Freedom as an Online Freelancer Rating: 5 out of 5 stars5/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5The Digital Marketing Handbook: A Step-By-Step Guide to Creating Websites That Sell Rating: 5 out of 5 stars5/5Coding For Dummies Rating: 5 out of 5 stars5/5Introduction to Internet Scams and Fraud: Credit Card Theft, Work-At-Home Scams and Lottery Scams Rating: 4 out of 5 stars4/5The Designer's Web Handbook: What You Need to Know to Create for the Web Rating: 0 out of 5 stars0 ratingsRemote/WebCam Notarization : Basic Understanding Rating: 3 out of 5 stars3/5How To Start A Profitable Authority Blog In Under One Hour Rating: 5 out of 5 stars5/5From Nothing Rating: 5 out of 5 stars5/5Hacking : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Ethical Hacking Rating: 5 out of 5 stars5/5Cybersecurity For Dummies Rating: 4 out of 5 stars4/5The Logo Brainstorm Book: A Comprehensive Guide for Exploring Design Directions Rating: 4 out of 5 stars4/5The Beginner's Affiliate Marketing Blueprint Rating: 4 out of 5 stars4/5Web Designer's Idea Book, Volume 4: Inspiration from the Best Web Design Trends, Themes and Styles Rating: 4 out of 5 stars4/5Six Figure Blogging Blueprint Rating: 5 out of 5 stars5/5C++ Learn in 24 Hours Rating: 0 out of 5 stars0 ratingsHow to Disappear and Live Off the Grid: A CIA Insider's Guide Rating: 0 out of 5 stars0 ratingsLearn JavaScript in 24 Hours Rating: 3 out of 5 stars3/5The Hacker Crackdown: Law and Disorder on the Electronic Frontier Rating: 4 out of 5 stars4/5Mike Meyers' CompTIA Security+ Certification Guide, Third Edition (Exam SY0-601) Rating: 5 out of 5 stars5/5How to Be Invisible: Protect Your Home, Your Children, Your Assets, and Your Life Rating: 4 out of 5 stars4/5How To Start A Podcast Rating: 4 out of 5 stars4/5
Reviews for Learning Phalcon PHP
0 ratings0 reviews
Book preview
Learning Phalcon PHP - Calin Rada
Table of Contents
Learning Phalcon PHP
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Getting Started with Phalcon
Installing the required software
Installing PHP
Installing Nginx
Installing MySQL
Installing Redis
Installing MongoDB
Installing Git
Installing Phalcon
The Apache and Nginx configuration files
Apache
The host file
Nginx
Understanding the framework's internals
The dependency injection
The request component
The response component
The logger component
The crypt component
The flash component
The router component
The config component
The view component
The session component
The cache component
Summary
2. Setting Up the MVC Structure and the Environment for Our Project
What is MVC?
Model
View
Controller
The MVC structure
Creating the structure for our project
PSR
Creating the configuration file and the Bootstrap
Preparing the initial DI interface and the router
Using the router component in a module
Create the base layout
Summary
3. Learning Phalcon's ORM and ODM
The main differences between SQL and NoSQL databases
Connecting to the database
ORM/ODM operations (create, update, delete, transactions, and validations)
Adding the routing information
Creating the controller and the actions
Creating the views
CRUD operations using ORM
CRUD – reading data
CRUD – creating data
CRUD – updating data
CRUD – deleting data
Using PHQL
Using raw SQL
Database transactions
A manual transactions example
An implicit transactions example
An isolated transactions example
ODM/MongoDB
ORM – drawbacks and caching
Summary
4. Database Architecture, Models, and CLI Applications
The database architecture
The User table
The UserGroup table
The UserProfile table
Models
The User model
The UserGroup model
The UserProfile model
Registering a new user
Creating a user profile
The Category model
The Category translation model
The Article translation model
The Article model
The Article-Category-Article model
Summary
5. The API Module
Using APIs – recommended practices
Enabling SSL on our local machine
Creating the module structure
Writing a fully functional REST module with Phalcon PHP
Articles
Securing an API
Using SSL
Adding an API key for extra protection
Limiting the number of requests per second from the same IP
Limiting access to resources such as DELETE, PUT, and POST for authenticated users
Documenting the API
Installation
Usage
Summary
6. Assets, Authentication, and ACL
Assets management
Developing an authentication system
The database structure
Models
Securing the application using the ACL component
Summary
7. The Backoffice Module (Part 1)
Editing the main layout
common/topbar.volt
common/sidebar.volt
Cleaning the Core module
Hashtag CRUD
The hashtag controller within the API module
A common method to reduce code duplication
Retrieving the data
The layout structure
The hashtag form
The hashtag controller
The hashtag manager
The View template for the add() method
Improving the database table structure and adding validation
Editing hashtags
Deleting hashtags
Category CRUD
The Category form
Creating the Category templates
list.volt
add.volt
edit.volt
delete.volt
Creating the Category controller
Creating the Category manager
Summary
8. The Backoffice Module (Part 2)
User CRUD
Creating the controller (API)
The user controller from the Backoffice module
The user form
The user manager
User templates
Article CRUD
The Controller (API)
The Article controller from the Backoffice module
The Article form
The Article manager
Summary
9. The Frontend Module
The Frontend layout and basic functionality
footer.volt
paginator.volt
navbar.volt
layout.volt
Modifying BaseController.php
The Article item template
Retrieving articles from a category
Implementing ElasticSearch
Installing ElasticSearch
Enabling a client in DI
Indexing (storing) documents
Implementing MongoDB
Mongo models
modules/Core/Models/Mongo/BaseCollection.php
modules/Core/Models/Mongo/ArticleLog.php
Summary
10. Going Further
Uploading files with Phalcon
Using the Annotation router
Summary
Index
Learning Phalcon PHP
Learning Phalcon PHP
Copyright © 2015 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: August 2015
Production reference: 1210815
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78355-509-3
www.packtpub.com
Credits
Author
Calin Rada
Reviewers
Altaf Hussain
Stephan A. Miller
Dilanka Somarathne
Commissioning Editor
Kunal Parikh
Acquisition Editors
Harsha Bharwani
Rebecca Youe
Content Development Editor
Amey Varangaonkar
Technical Editor
Menza Mathew
Copy Editor
Vikrant Phadkay
Project Coordinator
Bijal Patel
Proofreader
Safis Editing
Indexer
Tejal Daruwale Soni
Production Coordinator
Aparna Bhagat
Cover Work
Aparna Bhagat
About the Author
Calin Rada is a full-stack developer with over 10 years of experience in web development; system architecture; database modeling; the setup, configuration, and administration of servers and hosting systems; and understanding customer and business needs. He is always interested in learning new things and working with new technologies.
I'd like to thank my family and all the people involved in writing this book.
About the Reviewers
Altaf Hussain is an electrical engineer on paper and a software engineer at heart. He is an e-commerce and mobile applications enthusiast. He acquired his BE degree in electrical engineering (with specialization in computers and communication) from Pakistan. He then worked for numerous organizations as a backend developer and moved to Saudi Arabia to work as a software engineer.
Currently, Altaf is working in the fashion industry at Shy7lo.com. He manages dedicated servers, different VPSes, Staging Servers, and GitLab instances for fast deployment. As a senior team member, he is responsible for creating cross-platform mobile applications and APIs. He also works on different caching systems, such as Varnish and Full Page Cache. In his free time, Altaf writes posts for http://www.programmingtunes.com.
Stephan A. Miller is a software engineer from Kansas City, Missouri, USA. He is currently working for Kinetic Supply Company. He has worked with open source software technologies for over a decade. Some of the languages that he uses are PHP, JavaScript, and Python. He also uses various frameworks in these languages, including Phalcon, Zend, Laravel, jQuery, AngularJS, and Flask. Stephan has written Piwik Web Analytics Essentials and Getting Started with Phalcon for Packt Publishing.
Dilanka Somarathne has worked with the LAMP stack for 2 years. He always tries to learn something new. He performs experiments in PHP to find out the best PHP framework for programming. He also conducted a tech talk session in benchmarking several PHP frameworks at his previous organization, thinkCube Systems, for which he received good feedback from the audience and appreciation from other technical leads and architects. Dilanka has experience of working on Laravel, Zend Framework 2, CodeIgniter, and Phalcon. He has worked on Node.js and Angular projects too.
Phalcon is a new and very fast PHP framework. He started following and learning Phalcon after he attended a Phalcon meetup. As his first step, he created a small application with Phalcon. Because of his amazing experience with the application, he was able to get a clear idea about it.
I feel fortunate to get a chance to join the reviewing panel of Packt Publishing. Leena Purkait gave me this awesome chance. I would like to take this opportunity to thank her. Then, Bijal Patel joined the team. From the first day, she has been very helpful and has always replied to my e-mails patiently. Thank you very much, Bijal.
Working as a Phalcon reviewer for Packt Publishing was a really good experience for me. Thank you very much guys for giving me this huge opportunity.
www.PacktPub.com
Support files, eBooks, discount offers, and more
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Free access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Preface
Phalcon is the fastest PHP framework out there, and it is delivered as a C extension. More than that, you will find it very easy to learn. This book will present in detail the most common and useful parts of Phalcon PHP, as well as guide you to lean towards making the right decision when developing a Phalcon-driven application.
Learning Phalcon PHP is an interesting journey that starts with guides for installing the required software and preparing the working environment and project structure, and continues with a step-by-step approach development of each module.
By the end of this book, you will have developed a simple but fully functional news website and gained advanced knowledge on how Phalcon works.
What this book covers
Chapter 1, Getting Started with Phalcon, introduces the Phalcon Framework. In this chapter, you learn how to install and configure Phalcon.
Chapter 2, Setting Up the MVC Structure and the Environment for Our Project, helps you get to grips with the basics of MVC (Model-View-Controller) and setting up the work environment.
Chapter 3, Learning Phalcon's ORM and ODM, is about Phalcon's ORM (Object-relational Mapping) and ODM (Object-Document Mapper). You learn how to connect to a database and create models and relations between them.
Chapter 4, Database Architecture, Models, and CLI Applications, teaches you how to create the database architecture and the models needed for our project. You also learn about Phalcon CLI and develop a simple CLI application.
Chapter 5, The API Module, helps you start the development of a RESTful API module.
Chapter 6, Assets, Authentication, and ACL, explains assets management (JavaScript files, style sheets, and images), and you create a simple authentication system based on an ACL (access control list).
Chapter 7, The Backoffice Module (Part 1), shows you how to develop CRUD operations. This first part is about CRUD for categories and hashtags.
Chapter 8, The Backoffice Module (Part 2), is a continuation of the previous chapter. Here, you develop CRUD operations for users and articles.
Chapter 9, The Frontend Module, helps you develop the frontend template. You learn how to implement Elasticsearch and Mongo to improve the speed of your application.
Chapter 10, Going Further, teaches you common operations, such as file uploads and annotations.
What you need for this book
The most important thing that you need is some knowledge of PHP 5.3 or later and Linux environments (this book is written based on Ubuntu/Debian). If you are not using a Linux distribution, or you are using a distribution other than Ubuntu/Debian, you will need to look up their official documentation to install the required software.
Who this book is for
If you are an intermediate PHP developer with some basic knowledge of installing and configuring your environment, then this book is for you. Familiarity with PHP frameworks will make your life easier.
Conventions
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text are shown as follows: Deleting data is easier, since we don't need to do more than calling the built-in delete() method.
A block of code is set as follows:
$di['session'] = function () {
$session = new Phalcon\Session\Adapter\Files();
$session->start();
return $session;
};
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
public function registerServices(\Phalcon\DiInterface
$di) {
$config = include __DIR__ . /Config/config.php
;
$di['config'] = $config;
include __DIR__ . /Config/services.php
;
}
Any command-line input or output is written as follows:
$ cd modules/Frontend/Views/Default $ mkdir index $ cd index $ touch index.volt
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: Going back to the article list, you will see the new title, and the Updated column will have a new value.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to <feedback@packtpub.com>, and mention the book title via the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <copyright@packtpub.com> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
Questions
You can contact us at <questions@packtpub.com> if you are having a problem with any aspect of the book, and we will do our best to address it.
Chapter 1. Getting Started with Phalcon
What is Phalcon? Let's start by quoting from the documentation of the official website (http://phalconphp.com/):
Phalcon is an open source, full stack framework for PHP written as a C-extension, optimized for high performance.
Version 2.0 of Phalcon was released in April, and it was developed with a new language called Zephir (http://zephir-lang.com/). Zephir was designed especially for developing PHP extensions, and it is quite user friendly for both (PHP and C) developers.
There are many frameworks out there. The main reasons why we choose Phalcon were for its steep learning curve, speed, and because it is decoupled. (We can use any of its components independently.) If you have some knowledge of the Model-View-Controller (MVC) and some experience with any Object-Relational Mapping (ORM), you will find working with it pretty straightforward.
We will start our journey with this first chapter where we will:
Configure our web server
Install Phalcon
Discuss a bit about how Phalcon works
Before starting, we assume that you are using a *nix environment. Personally, I feel comfortable with Debian distributions, especially Ubuntu, which I am using on a daily basis; so, the installations steps that we will talk about are for Ubuntu. The OS is a matter of personal choice, but I highly recommend any *nix distribution for development. (Even Microsoft decided to open source their ASP.NET for Linux early this year)
For other types of OS, you will have to search their official documentation, in terms of how to
. This book is intended to be about Phalcon and tutorials on installing different software on different kinds of OS are out of the scope of this book.
Note
Here is the list of URLs that contain installation instructions for different operating systems:
http://docs.phalconphp.com/en/latest/reference/install.html#windows
http://docs.phalconphp.com/en/latest/reference/install.html#mac-os-x
http://docs.phalconphp.com/en/latest/reference/install.html#freebsd
Senior developers might not agree with me on certain subjects or certain techniques and/or recommendations. In general, as a developer, I think you should analyze what is suitable for you and develop a platform according to your (or client) requirements. In addition, most importantly, there is no such thing as The Perfect Solution
. There is always room for improvement.
Installing the required software
We need to install the following software that we are going to use in this book:
PHP
Nginx and Apache
MongoDB
MySQL
GIT
Redis
Phalcon
Installing PHP
You have probably already installed PHP on your system since you are reading this book. However, just in case you haven't, here are the simple steps to quickly install the latest PHP version (Phalcon is running on PHP version >= 5.3). I recommend you to use the Personal Package Archive (PPA) from Ondřej Surý (https://launchpad.net/~ondrej/+archive/ubuntu/php5) because it has the latest PHP version available on it:
$ sudo add-apt-repository ppa:ondrej/php5 $ sudo apt-get update
If you don't want to use this step, you can simply install PHP from the official repositories:
$ sudo apt-get install php
Apache will be installed by default with PHP. However, if you want Nginx instead of Apache, you must install PHP in a certain order.
The following command will automatically install PHP