PHP is a single inheritance language. This limitation created challenging situations for a lot of PHP developers. Thankfully this limitation was solved in PHP 5.4 with the introduction of traits.
Here is a brief overview on traits.
Traits are a very handy way of reusing code in PHP. This allowed to overcome the single inheritance limitation that PHP had. It enabled developer to reuse methods across several independent classes residing in different class arrangements. Traits reduce complexity, and allows to helps prevent problems that were associated to multiple inheritance and mixins.
Traits are very similar to classes, but are intended to group up functionality in a smooth and uniform way, and they cannot be instantiated on their own. It is an expansion to traditional inheritance and enables a horizontal scaling behavior; as in, utilization of class members without having to require inheritance.
Now, onto what you came here for.
I like to think that I am organized. I’ve been told so, but I think that there is always room for improvement. Therefore when adding traits to a project I like to create a
traitsdirectory under myappdirectory. Placement is not really that important, but I like to keep it clean (for example you could create the traits folder under your library folder). Here is how to looks:
The next step after creating the folder is integrating it into our working environment. Open the /app/config/config.php file and add a reference to the directory under application.
return new \Phalcon\Config([
'siteName' => getenv('SITE_NAME'),
'siteUrl' => 'http://'.getenv('SITE_NAME'),
'controllersDir' => getenv('BASE_DIR') . 'app/controllers/',
'modelsDir' => getenv('BASE_DIR') . 'app/models/',
'viewsDir' => getenv('BASE_DIR') . 'app/views/',
'pluginsDir' => getenv('BASE_DIR') . 'app/plugins/',
'libraryDir' => getenv('BASE_DIR') . 'app/library/',
'cacheDir' => getenv('BASE_DIR') . 'app/cache/',
'traitsDir' => getenv('BASE_DIR') . 'app/traits/'
'baseDir' => getenv('BASE_DIR'),
'baseUri' => '/'
]
]);
Next, open the /app/config/loader.php file and add register the namespace reference.
$loader->registerNamespaces(array(
'Project\Controllers' => $config->application->controllersDir,
'Project\Traits' => $config->application->traitsDir
));
$loader->register();
That’s it! Well, aside from actually creating a trait and applying for use. Take this trait for example:
namespace Project\Traits;
trait HttpBehavior
{
/**
* Set JSON response for AJAX, API request
*
* @param string $content
* @param integer $statusCode
* @param string $statusMessage
*
* @return \Phalcon\Http\Response
*/
public function jsonResponse($content, $statusCode = 200, $statusMessage = 'OK')
{
// Encode content
$content = json_encode($content);
// Create a response since it's an ajax
$response = new \Phalcon\Http\Response();
$response->setStatusCode($statusCode, $statusMessage);
$response->setContentType('application/json', 'UTF-8');
$response->setContent($content);
return $response;
}
}
Now, to use it just go where you want to include it and invoke it:
namespace Project\Controllers;
class IndexController extends ControllerBase
{
/**
* Invoke Traits
*/
use \Project\Traits\HttpBehavior;
/**
* Does something...
*
* @param $someVar
*
* @return \Phalcon\Http\Response
*/
public function doSomethingAction($someVar = '')
{
// Do this and that and get something to return
$content = [
'id' => 1,
'message' => 'something'
];
// Return response
return $this->jsonResponse($content);
}
}
Very simple and elegant.
The use of environment variables is quickly becoming a staple for many PHP developers. It is a way through which configurations can be easily added to the development of applications with very little work or hassle.
This is a small article to show you how to implement environment variables in your PhalconPHP configuration.
Some notes before you continue reading: I currently work using PHP 5.6 in my development environment. Therefore expect not to see array() when an array is being used or define. Expect to see the new brackets method ([]).
We will be using Vance Lucas’ phpdotenv library (the link will take you to his GitHub repository). You can follow the instructions for installing the library using Composer.
Once you have the library installed you will want to create a .env file, which is where you will define all your configuration values. It is a good idea to create this file in the user root directory (for example: /home/user/).
//This is an example of a `.env` file:
DOMAIN=yourdomain.com
BASE_DIR=/home/user/
PRODUCTION=1
DATABASE_HOST=
DATABASE_USER=
DATABASE_PASS=
DATABASE_NAME=
BEANSTALK_HOST=
BEANSTALK_PORT=
BEANSTALK_PREFIX=
MEMCACHE_HOST=
MEMCACHE_PORT=
REDIS_HOST=
REDIS_PORT=
EMAIL_HOST=
EMAIL_PORT=
EMAIL_USER=
EMAIL_PASS=
With this you can set all necessary configuration values. Do keep in mind that different development systems can (and probably will) have different values for the configurations. Your .env file is to be kept off your versioning system. So, in order to let the other developers know what values they NEED to set for the configuration all you need to do is create a .env.example file which is an exact copy of .env, except that none of the variables will have values.
This skeleton file will let the developer know what he has to provide for the system in order for it to work properly.
Next, we will load the environment variables into PhalconPHP. Locate the loader.php file (located in INSTALLATION_DIR/app/config/loader.php), open it in your editor of preference and append these lines to the end of the file:
/**
* Composer autoload
*/
include __DIR__ . '/../../vendor/autoload.php';
/**
* Environment variables
*/
$dotenv = new Dotenv\Dotenv(__DIR__ . '/../../');
$dotenv->load();
IMPORTANT This environment variables loader has to go AFTER you include Composer’s autoload.php file. Look at the code above carefully.
With this we are ready to load our environment variables into PhalconPHP’s configuration. So go ahead and open the config.php file (in the same folder as the loader.php file), and use the environment variables like this:
[
'adapter' => 'Mysql',
'host' => getenv('DATABASE_HOST'),
'username' => getenv('DATABASE_USER'),
'password' => getenv('DATABASE_PASS'),
'dbname' => getenv('DATABASE_NAME')
],
'application' => [
'controllersDir' => getenv('BASE_DIR') . 'app/controllers/',
'modelsDir' => getenv('BASE_DIR') . 'app/models/',
'viewsDir' => getenv('BASE_DIR') . 'app/views/',
'pluginsDir' => getenv('BASE_DIR') . 'app/plugins/',
'libraryDir' => getenv('BASE_DIR') . 'app/library/',
'cacheDir' => getenv('BASE_DIR') . 'app/cache/',
'baseUri' => '/',
'baseDir' => getenv('BASE_DIR')
]
]
That’s it! Couldn’t have been easier! With this in place you can now commit ALL project files without having to worry for the configurations the different systems need.
We are excited to announce the release of Phalcon 2.0.6!
This version contains mostly bug fixes as well as improvements to the 2.0.x series.
We are happy to announce that Phalcon 2.0.5 is released.
This version contains bug fixes and small improvements to the 2.0.x series.
As part of our three to five weeks minor release schedule, we are excited to announce that Phalcon 2.0.4 has been released!
The number of improvements and bug fixes are a lot more compared to other releases in the 2.0.x series:
As part of our regular release schedule, we are happy to announce that Phalcon 2.0.3 has been released!
This version contains many bug fixes as well as new functionality that derived from community NFRs.
Phalcon 2.0 was launched a month ago. It is the new version of the fastest PHP framework, PhalconPHP. Now that some time has passed we’d like to talk about the differences between both versions, why you should upgrade to Phalcon 2.0, and why you should consider it as a development framework.
PhalconPHP is a PHP framework much like Laravel, Symfony, CakePHP, and Codeigniter (to name a few). Even though there are many frameworks Phalcon has a huge advantage over the rest: it’s source code is written in C and it runs as a PHP extension. That is the advantage it possesses. Since it’s written in C and compiled as an extension Phalcon does not have to be interpreted for each request. Instead it works like a component of PHP. It could be argued as if PHP had its own native framework since you do not have to include files or libraries to call its components. This gives Phalcon a huge boost in both speed and performance.
Example of code using Phalcon:
use Phalcon\Mvc\Controller;
class IndexController extends Controller
{
public function indexAction()
{
echo "Hello! Phalcon v2";
}
}
However, being a framework written in C is both Phalcon’s greatest strength and weakness. Most PHP developers do not have knowledge of C as a programming language. This has greatly limited the amount of contributors Phalcon has had; slowing the rate at which it can grow and mature.
namespace Utils;
// Zephir Code
class Filter
{
public function alpha(string str)
{
char ch;
for ch in str {
echo ch, "\n";
}
}
}
Running your code on PHP
$f = new Utils\Filter();
$f->alpha("hello");
Phalcon’s creators have been conscious of this big hurdle, and they have been working hard on a solution that could very well impact the PHP community at a grander scale. Zephir was created exclusively for the development of PHP extensions and is the core for Phalcon 2.0. Zephir is a new language with similar structure to PHP that will allow the PHP community to actually participate in Phalcon’s development, and in turn help Phalcon evolve and mature quicker, offering a wider variety of options and components.
That’s right. Phalcon 2.0 was written in Zephir. That is the main difference between both versions. While Phalcon1 was written in C and compiled as an extension, Phalcon 2.0 is written in Zephir, which is in turn compiled into a PHP extension in C. At its core, Phalcon 2.0 is simply Phalcon 1.3 rewritten in Zephir. This was done to prove two things: that Zephir is reliable and that extensions for PHP can now be developed more easily.
It is a simple matter of code integration and security. It is never a good idea to work off of old frameworks versions. The main force behind the advice for upgrading is simple: Phalcon 2.0 is Phalcon 1.3. Upgrading to the latest version (2.0.2 at the moment of this article) shouldn’t be a problem. Backwards compatibility is guaranteed.
This new version of Phalcon guarantees several things for the community:
It will allow the framework to grow quicker because more people will be able to contribute.
There is a new programming language with the ability of allowing everyone to write PHP extensions with ease.
At its core Phalcon 2.0 is still Phalcon 1.3, but written in Zephir.
You should consider it not only for it’s speed and performance, but also because it’s unshackled. You can organize your project in any way you want, following the latest tendencies the PHP community is adapting.
If you still have any doubts feel free to comment on them and we will answer your questions or concerns. Feel free to consult the cheat sheet or the PhalconPHP forums first to see if what you need is already answered there.
Zephir - [https://zephir-lang.com][https://zephir-lang.com]
The development of Phalcon has been accelerated since we released 2.0.0. More and more contributors find Zephir very easy to understand and work with, and as a result it is time to release Phalcon 2.0.2. This version includes many features, bug fixes and improvements in terms of performance: