33,59 €
Master Phalcon by implementing hands-on recipes using industry best practices with the Web and CLI interfaces
If you are a beginner-to-intermediate Phalcon developer who wants to level up or an advanced user who is seeking some new techniques and insight, then this book is perfect for you. This book will be relevant to you over a long period of time due to the mixed nature of this book in providing both abstract comprehension as well as specific examples meant to be usable in your projects. You will be able to experiment with each new aspect of integration in prebuilt recipes meant to best illustrate each specific feature. This will save you lots of time getting up to speed before attempting to integrate into a real application.
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.
An easy-to-start guide that provides
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 406
Veröffentlichungsjahr: 2016
Copyright © 2016 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 authors, 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: November 2016
Production reference: 1281116
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78439-688-6
www.packtpub.com
Authors
David Schissler
Serghei Iakovlev
Reviewer
Nikolaos Dimopoulos
Acquisition Editor
Reshma Raman
Content Development Editor
Parshva Sheth
Technical Editor
Rutuja Vaze
Copy Editor
Safis Editing
Project Coordinator
Ritika Manoj
Proofreaders
Safis Editing
Indexer
Tejal Daruwale Soni
Production Coordinator
Aparna Bhagat
Cover Work
Aparna Bhagat
David Schissler was born and raised in Northern California. He received a significant portion of his education from Santa Rosa Junior College, Chico State University, and ultimately received a Bachelor of Computer Science from Sonoma State University.
David started his career as a programmer working with VB.net before transitioning solely into web development. He is a longtime Linux user and is an avid supporter and user of completely open source development platforms, including, the firmware, operating system, programming languages, and text editors.
David is a world traveler who has lived on three different continents for extended periods of time. He is quite comfortable living out of a single bag while developing web software, writing books, and traveling the world.
I would like to thank Bill Wiggins for sharing our dreams and for my profound cafe experiences in many parts of the world. I would like to thank John Gudgeon for giving me that necessary kick and helping me evacuate my apartment so that I could jump onto that fateful sail boat heading south , and my father Jim Schissler for writing puzzle games for the TRS-80 that we hooked up to the living room television. I’d also like to thank everyone that has been supportive of my education and adventures.
Serghei Iakovlev has been working as a Ruby/PHP developer for over 7 years and has been specializing in web application development. As a supporter and advocate of Behavior Driven Development (BDD), he is also a member of the Codeception team.
Serghei can be found neck deep in innovative technologies, which introduced him to Phalcon. He is responsible for the coordination of bug fixes, testing, developer tools, incubator, and supports other Phalcon-related projects.
When he’s not working, Serghei enjoys watching documentaries, science fiction movies, and sometimes plays Mahjong or Go.
I’d like to thank my wife, Yaroslava, for her patience, encouragement, and assistance in translation of my part of the book. I’d also like to thank my technical leader, Andres Gutierrez, for creating such a wonderful framework, and my team mate, Nikolaos Dimopoulos, for his assistance in technical details and for all his recommendations. These people helped me get this book finished.
Nikolaos (Nikos) Dimopoulos has over 20 years of progressive experience in designing and developing applications. He is currently serving as a Senior Developer/Analyst for ITWorks Inc. Nikolaos has always been passionate about quality, testability, and good design. Throughout his career, he has been everywhere, from leading the Technical Cooperation Project Monitoring and Management System (TCPMMS) at the UN/International Atomic Energy Agency in Vienna, to being a main catalyst in the growth of a widely popular online community.
He is constantly curious about new technologies and finds ways to increase the performance of his applications. This led him to discover PhalconPHP a few years back. With his contributions, it was not long before he became a member of the core team, helping with documentation, tests, and other duties.
In his free time, he enjoys time with his family, contributes to open source, writes his thoughts on his blog, and tries to keep up to speed with technology.
I would like to thank my family for all the support they have given me throughout the review of this book. Without it, I would have never made it.
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 <[email protected]> for more details.
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://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Phalcon was created to maximize the performance of PHP applications. Along the way, Phalcon adopted many industry best practices and became a model of what a modern PHP application should look like.
In the beginning, Phalcon was written purely in C language, and this made it difficult for many types of developers to contribute to the project. Starting with version 2.0, the project was rewritten in a new PHP resembling language called Zephir, which allowed many more people to contribute. Recently, with the release of Phalcon 3.0, the framework has begun its first period of long-term support and adherence to semantic versioning.
Chapter 1, Getting Used to Phalcon, demonstrates how to start a Phalcon project, configure your IDE to make your work on the project easier, and brings to light the main principles you must understand while dealing with the Phalcon Framework.
Chapter 2, Structuring Your projects, covers the project structure. This chapter demonstrates one of the optional versions of the project structure and helps configuring routing and introduces how to use middlewares in your project.
Chapter 3, Processing Requests, takes you through the process of a normal web request as well as explores the Websockets and EventSource request models.
Chapter 4, Dealing with Data, teaches you to the skills to deal with real data using relations, PHQL, or raw SQL and how to use customized database adapters.
Chapter 5, Presenting Your Application, introduces Views. It covers aspects such as using HTML fragments, working with layout structure, viewing snippets, as well as working with Volt Template Engine.
Chapter 6, Making Use of Advanced Features, covers the strong points of Phalcon Framework, such as dependency injection, validation, working with sessions, event management, complex routing, and so on.
Chapter 7, Debugging and Profiling, demonstrates how to handle the unusual and troublesome aspects of a project.
Chapter 8, Fine Tuning and Optimizing, talks about how to optimize a project for high throughput and reliability.
Chapter 9, High Performance Applications with Phalcon, covers the work with high load projects. You will learn how to work with the message queues and caching. This chapter also introduces Zephir language. It covers the main principles of creating extensions in Zephir and the Phalcon Framework enhancement.
Chapter 10, Securing Your Applications, avoids common attacks and implement an ACL with password hashing.
This book requires PHP 5.5 or later, a web server, database server, and command line access. Although any web and database server can be used in this book, the reader will have a much easier time with Apache and MySQL. This book makes extensive use of the Phalcon Developer Tools to create projects, and this will require command line usage. Some recipes in this book will require specific PHP extensions and so the reader will need to have the ability to install these extensions on their machine as well as the ability to restart the web and database server, to read the web server logs and many other things that require administrator access. Windows, Mac, and Linux are all supported environments.
If you are a beginner-to-intermediate Phalcon developer who wants to level up, or an advanced user who is seeking some new techniques and insight, then this book is perfect for you. This book will be relevant to you over a long period of time due to the mixed nature of this book in providing both abstract comprehension as well as specific examples meant to be usable in your projects. You will be able to experiment with each new aspect of integration in prebuilt recipes meant to best illustrate each specific feature. This will save you lots of time getting up to speed before attempting to integrate into a real application.
In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There’s more, and See also).
To give clear instructions on how to complete a recipe, we use these sections as follows:
This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book’s title in 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 at www.packtpub.com/authors.
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.
You can download the example code files for this book 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.
You can download the code files by following these steps:
You can also download the code files by clicking on the Code Files button on the book’s webpage at the Packt Publishing website. This page can be accessed by entering the book’s name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Phalcon-Cookbook.We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
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 could 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 to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted 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 <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
In this chapter, we will cover the following topics:
Despite the fact that Phalcon is a framework for PHP application development, it isn't itself PHP-based. Therefore, some difficulties may appear when using syntax highlighting or code autocompletion. In this chapter, we will try to study how to set up autocompletion in a modern Integrated Development Environment (IDE) and how to enable code autocompletion.
An essential step in the architecture process when developing an application is a clear understanding of the project directory structure and the role of each of the directories. We will use a variation of a Phalcon project directory structure, which is easy to deploy and upgrade. The directory structure, which we work with in this chapter, isn't a rule set in stone. In future you will, time after time, use different directory structures, which will be different than the one we will be using. That structure is only one of the options and a starting point for your needs, and it easily responds to changes caused by certain technical conditions.
Phalcon is not only the fastest framework in the world, it is one of the easiest frameworks. As a rule, you don't need any special knowledge or additional software. However, when developing an application with Phalcon, you will need to create a base system configuration and application skeleton. In this chapter, we will learn how to deploy an application with the use of Phalcon, how to make its base configuration, and how to create a flexible and efficient application skeleton, which you can use in future.
Any object-oriented PHP application needs classes. You have to tell your class autoloader where your classes are situated and which way they can be searched for. We will look at some possible options of class auto-loading in Phalcon and their usage methods.
Many developers, despite their experience, have difficulty when working with a Request component. Phalcon isn't an exception. We will discover how to make a base application configuration so that Phalcon starts handling requests. We will learn how Phalcon handles these requests and in what sequence they are executed. We will learn which components take part in arequest life cycle, where it is possible to catch the request, how to specify its state, as well as how to take any suitable actions.
Most IDEs have some form of code completion as part of the program. To enable auto-completion for Phalcon's namespaces, we will need to help the IDE recognize those namespaces. We will also see how to enable Volt syntax highlighting and Phalcon API auto-completion for major IDEs.
To get started, we should have Git installed. To enable auto-completion in your IDE, you need to get the Phalcon stubs. For these purposes, clone the Phalcon Developer Tools repository:
The following are the steps needed to complete this recipe.
If you have Sublime Package Control, you know what to do. If not, well, it's a package manager for Sublime Text, and it's awesome!
After installing Sublime Package Control and restarting the editor:
For manual installation, clone the Volt syntax highlight for the Sublime Text 2/Textmate repository:
Depending on your OS, copy the volt-sublime-textmate/Volt directory to any of the following locations:
Some IDEs need help understanding the framework syntax. To get the IDE to understand, we download a list of all the Phalcon stubs. Then, when we add it to the include path, NetBeans (or PhpStorm) will automatically check the file and show us the autocomplete options. To enable the Volt or Zephir syntax highlight, we have to configure our IDE or text editor accordingly.
In this recipe, we will take a brief look at the commonly used directory structure of a single module application. A structure of this type is aimed at providing a great starting point for different applications.
We don't need any special means to implement this recipe. We will create the project structure on site, at the development stage. Important points of this recipe are the names of directories and their location.
Follow these steps to complete this recipe:
The project root directory contains the following directories: app, public, and .phalcon (note that the last one has a point at the beginning of its name).
In the app directory, there will be, as you would expect, the main application code. We will describe this folder in detail shortly.
The public directory will contain the entry point of your application and directories for various static assets (JavaScript files, images, and CSS files).
The .phalcon directory will be used by the Phalcon developer tools for internal purposes (migration creation, code generation, and so on). This is the Phalcon system directory. There is no need to create something in it.
The app directory contains a subdirectory for controllers as well as their views and models. Additionally, there is the tasks directory, which is intended for cli tasks, the library directory for the general application components (plug-ins, helpers, and other custom classes), the logs directory, where we will store our log files, and the cache directory for storing cached data of different application components.
In the cache directory, there are the following directories: annotations to store the file cache of model annotations, data to store common file cache, metadata to store the model structure cache, and volt to store the view cache.
Note that we have created different directories to store screenshots. These directories are utilized when we are using the File Cache. If you will be using a cache adapter other than the File one, you don't need to create the directory structure here.
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.
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.
Follow these steps to complete this recipe:
