Choose the right PHP framework
A PHP framework gives you common structures to normalise web apps, assist productivity, reduce repetitive coding and create more stable sites. Kai Chan helps you pick one.
A PHP framework provides a foundation where developers’ code can be neatly arranged. Documentation, common problems, solutions, tips and advice can be shared online in an open source fashion.
In the days before web frameworks, it was common to see sites written in a proprietary fashion. Different coders would employ their own arsenal of techniques and methodologies in arranging their code and designing their architecture. This would create a number of issues: lack of documentation, complex proprietary frameworks – or the common case of ‘what happens when a programmer leaves?’
Developers often tried to solve the problem of organising code by following the process of ‘separation of concerns’, basically breaking bigger problems down into smaller ones and marking out distinct working boundaries between sections of code.
Templating engines provided another useful tool to help web app development. Smarty Template Engine is a longstanding, popular library enabling easy separation of the two areas of code web devs often deal with: the generation of content (aka the business logic) and how it’s displayed (the presentation markup or view).
Robust websites
Frameworks really came into use in 2004, when they offered themselves as a comprehensive solution to building robust websites. Most of the popular PHP frameworks are predominately based around the design methodology called model-view-controller or MVC for short. It’s probably no coincidence that the well-known Ruby on Rails MVC framework launched around mid-2004; this will undoubtedly have been an inspiration for many other PHP frameworks.
One of the first PHP frameworks on the scene was the Mojavi Project, sadly no longer active. Nowadays, however, there are many PHP frameworks fighting for our attention. In this article we’ll cover the four major PHP frameworks that are now often used in the industry: CakePHP, CodeIgniter, Symphony and Zend.
01. What exactly is a PHP framework?
So what is a PHP framework? Essentially, it’s a set of PHP classes and functions that developers adhere to when developing a site. The MVC paradigm can be viewed as an extension to templating engines. Here is a quick explanation:
- Model: The model contains the server business logic code. This usually involves the reading and writing to a database in addition to some pre- or post-processing. For example: ‘A user enters a comment, but before we insert it into the database, we need to do a spam check with akismet.com; if it passes we can do the insert.’
- View: This is where you present the output to the user in a particular format, most often HTML markup, although it can be the JSON or XML format. For example: ‘We need to display all the comments for a forum topic, the model fetches all the comments and are then read and formatted by the view.’
- Controller: The controller is essentially the manager. It first intercepts the URL, then calls the correct models and views before presenting it to the browser, mobile device or an API caller. For example: ‘In displaying all the comments for a topic, the controller makes the actual call to the model and then passes the model data to the view, which then generates the HTML output. This generated view is then shown to the calling browser by the controller.’
A PHP framework gives you a well defined coding template where you need to place certain types of code. The following ultra simple PHP code will give a coder’s view on how MVC works in general. It displays the current weather where you are!
Get the Creative Bloq Newsletter
Daily design news, reviews, how-tos and more, as picked by the editors.
<?php
// The weather "controller"
function controller_weather() {
$type = model_weather();
echo view_weather( $type );
}
// Get the current data/weather, the "model"
function model_weather()
// get the data
$status = 'Look out the window!';
return $status;
}
// Generate HTML presentation, the "view"
function view_weather( $type ) {
// design and layout should be here
return ‘<b>Weather where you are:</b>
'.$type;
}
// intercept URL and call the relevant controller
if ( strstr( $_SERVER[ 'REQUEST_URI' ], '/weather/'
) ) {
controller_weather();
}
?>
A common mistake is mixing code between controller and model. Business code should ideally all be in one place: in the model, or indeed a thirdparty library. A good question to ask yourself is, ‘would other controllers use this logic; is it a generic piece of code?’ If yes, then it should belong in that one place, the model being the most common one.
There is still some confusion as to where business logic should be placed, in controllers or models. Just Google ‘fat models skinny controllers’. Much of the problem stems from the fact that ‘business logic’ is a fuzzy term.
Another good way to have a clean separation between business logic and view is to develop an API to facilitate integration to other systems. This more or less forces a web team to build a robust system since the same piece of business logic must be adaptable to different scenarios. In addition, consideration of this needs to be in place right from the start of a project.
The view is much easier to demarcate: you can only have programming display syntax in the view. Controllers and models should never contain any presentation syntax, for example <br/>. You will be in big trouble if you do!
02. How can it help?
Using a PHP framework may not be the answer to every project. You need to look at your environment and judge how well a PHP framework can fit in. Here are some pros and cons in using frameworks:
Pros
- PHP frameworks can be used as a rapid application development method, enabling quick prototypes to be developed.
- As each project is based on a similar structure, it allows for a faster development cycle.
- Developers can easily jump from project to project without worrying too much about the structure of the code.
- Plays well with Agile software development.
- The underlying code will change less often, resulting in a more stable site.
Cons
- Some frameworks have a steep learning curve.
- It can be difficult to find developers with experience of a particular framework.
- Not all frameworks are bug free
- Hackers can exploit weaknesses in frameworks.
- Different frameworks’ interpretations and supporting libraries of the MVC principle can vary.
PHP frameworks and frameworks in general are chiefly within the domain of developers. However, other parties within a web project have different needs when it comes to frameworks:
- Managers/owners: The three different domains of model-view-controller within a framework give managers a way to divide tasks into manageable chunks. For example, a developer working within the Products model need not worry about how it’s used externally. The external presentation is dealt with by the View. A framework in essence enables easier parallel development. Agile development is a project management method that goes well with frameworks. With many tools available in virtually all frameworks and a clean structure managers can understand, rapid development and turnarounds are the norm.
- Designers: The visual representation will always be a difficult task to merge into code. Using an MVC framework helps but the task is still tedious and difficult. Developers need to split a design into its individual components and splice it into the appropriate views. This is where CSS frameworks can sometimes help.
03. Convention over configuration
For frameworks to deal with the multitude of scenarios, configuration setting is an important area. Most frameworks opt for the ‘convention over configuration’ design solution. For example, if the PHP class for a model is called model_students, the database table should be named students and the PHP class for the corresponding view should be called view_students. This lowers the complexity of configuration settings, as seen in the previous PHP weather example.
Configuration files offer more flexibility and control; the drawback is they can add complexity in comparison to convention over configuration.
The following is a configuration snippet of code from Symfony’s routing file:
# app/config/routing.yml
hello:
pattern: /hello/{name}
defaults: { _controller:
AcmeHelloBundle:Hello:index }
The corresponding code is simply a ‘hello world’ script: if the URL is, for example, example.com/hello/Bob, then the output is ‘Hello Bob’. The snippet of syntax above matches the URL with the appropriate piece of controller code.
04. View separation
One of the chief problems that the use of MVC frameworks solves is separating business logic from the output of data.
Mixing some code into presentation logic is inevitable when using a PHP framework. However, you want to keep any presentation markup out of the controller – and, more importantly, the model. So in our simple weather example, if we decide to add the bold HTML tag <b>, it would be considered bad practice because it will probably cause problems if the presentation is in JSON or XML.
function model_weather() {
// This is bad!
// No presentation markup allowed in model!!
// Fix or else!
$status = '<b>Look out the window!</
b>';
return $status;
}
05. Database support
Web apps most often use a database to store permanent user data. All four major PHP frameworks have good support for MySQL and other common database drivers such as Oracle and MS Server. There is a related software component called object-relational mapping (ORM), which some PHP frameworks use. Symfony in particular makes heavy use of Doctrine, a third party ORM that can also be used in other PHP frameworks. ORM aims to simplify the database code within a web project.
06. Community
All the major PHP frameworks we’re discussing have community support; CodeIgniter is especially active. Pay attention to the number of tutorials for each PHP framework written by bloggers: a much needed resource in helping developers understand a PHP framework. Noteworthy fact: Symfony made a major version upgrade in 2011. Knowledge relating to the new version 2 may not be relevant; however, version 2 is a major change to a proven framework.
07. Documentation
Documentation is vital as a point of official reference. There shouldn’t be a need to dig through the source code to see how things should work, though it is a common occurrence. Documentation should have good examples to go with each feature. What’s more, a good PHP framework should also have a variety of books, forums and video tutorials.
08. Additional PHP framework features
- Helper functions: These are often plain PHP functions that perform one task only, email validation for example.
- Caching: This is getting more important as more content is accessed in a wider variety of ways. All PHP frameworks have varying degrees of caching mechanisms. Many web owners also opt for thirdparty tools such as Squid.
- Unit testing: This enables automated testing of code within your app. For major projects you should try to add some unit testing. All the PHP frameworks reviewed either have their own unit testing methods or use PHPUnit, which is pretty much the de facto PHP testing suite.
- Form generation: Here PHP frameworks can really shine. Forms are so prevalent in web apps that most frameworks have generation or validation features to aid developers in adding web forms.
- Session: The session features within PHP already work quite well. Most PHP frameworks add features on top of the existing PHP session. Zend, in particular, has good session control functions.
- Templating: This refers to how code is organised within a view. It tries to answer the question, ‘what’s the best way to organise code within the view?’. Smarty Template was an early solution prior to MVC frameworks. In the context of this article, Symfony is the only framework using a templating software, called Twig. It’s very similar to Smarty Template and was developed by the same company as Symfony.
- Extending/third-party module: Third-party plug-ins and themes have been the driving force behind development platforms such as WordPress and Drupal. Some MVC frameworks aim to do the same; pretty much all of them have rudimentary third-party extensions or plug-ins, with the exception of CakePHP. Frameworks need to do more in this area.
- ACL: Access control and log-in management is a common feature of many web apps. All the frameworks provide varying levels of features relating to what is often called Access Control Lists (ACL). CodeIgniter is the only framework where you need to search the web for third-party ACL plug-ins.
09. Main contenders
There are well over 20 different open source PHP frameworks; this often causes a serious case of brain freeze. However, in recent years, the four major frameworks CakePHP, CodeIgniter, Symphony and Zend have gradually come to dominate.
This is down to long life, community support and documentation help. Features aren’t used because they mostly do similar things, and if a framework lacks a feature, it’s likely a third-party plug-in will be available. How one hammer is better than another is often a matter of personal philosophy, past experience or current working environment.
Out of the four frameworks, CodeIgniter and CakePHP very much belong together, with CodeIgniter the easiest to pick up. This is followed by Zend and Symfony, because they’re very similiar. Symfony has the steepest learning curve in comparison to Zend, owing to a greater body of knowledge that needs to be picked up.
1 CakePHP
Pros Active community; Cake Bakery (bakery. cakephp.org)
Cons Cake has very specific ways of doing things
This framework takes inspiration from Ruby on Rails and very much belongs to the KISS (keep it simple stupid) camp. Its framework structure is easy to understand. There are folders for controllers, models and views. Most web apps will have most of its code contained within these three folder types.
The highlight of CakePHP is the Cake Bakery where third-party developers can add their own code and share it with the community. CakePHP is a good middle ground, not as simple as CodeIgniter, but not quite as complex as Zend or Symfony.
CakePHP doesn’t have add-ons such as ORM or a template engine. Out of the four frameworks, this is the only one that doesn’t have corporate backing – but that could be seen as a plus point.
2 CodeIgniter
Pros Speed; very lightweight; large active community, good documentation
Cons Can allow too much freedom in coding
Created by EllisLab in Oregon and released soon after CakePHP, in 2006, this is great in projects where a best of breed approach is favoured. You can add other third-party software without feeling weighted down, and like CakePHP and Zend, it has a clear MVC folder structure which you can follow. CodeIgniter also gives developers more headroom to solve problems according to their thinking, unlike Zend or Symfony, in which you need to think in terms of the individual methodology.
3 Symfony
Pros ORM; has its own template engine
Cons Steep learning curve
Symfony, created by the French agency SensioLabs, definitely feels different. It promotes using ORM, a plus for heavy database work, and uses its own Twig template engine, also created by SensioLabs.
To get a feel, head to symfony.com, the version 2 site. Don’t get confused with the version 1 site, symfony-project.org; version 2 is the one to learn!
There isn’t an obvious MVC terminology within Symfony, though it does much the same thing as the other frameworks. It has a unique concept called Bundles, collections of related code or files that help separate web app features. Like Zend, code generation plays an important part in Symfony.
This is the most difficult framework to grasp, but with good community support, help is never far away. The model structure is different to many other frameworks: it promotes Doctrine as the entry point for the business logic model code.
4 Zend
Pros Good corporate software with longevity
Cons Design pattern concepts take time to grasp
Created by Zend, the firm behind the PHP engine, it was obvious this framework would be taken seriously. Zend has the features of a robust, corporate style software as well as related commercial products such as a commercial web server, support and its own IDE. In combination these make it a powerful way to develop web apps.
Zend is similar to CodeIgniter and CakePHP, but heavy documentation based on design pattern concepts can make it hard to get started with.
Zend is probably the most sought after framework when looking at PHP-related job descriptions, and has quite a few good features within it. The Lucene search feature brings commercial grade web search to an app; other highlights include form creation, data filtering and Internationalisation. But Zend is much more than a PHP framework; you benefit from the support, training, certification and related products.
10. Choosing a framework
Picking your framework can largely depend on project circumstances, and as with any tool is a personal philosophical choice. A one man agency may want a quick turnaround with a short learning curve; a large firm may prefer robust software that has the feel of Java – criteria Zend will meet.
Longevity is an important factor. It relates closely to documentation; frameworks with a long history have a greater pool of knowledge. Cost may also be an issue: frameworks with steeper learning curves, such as Zend or Symfony, will require skilled coders – which always means higher wages. Commercial support is often needed for large projects; Zend or Symfony are well placed to take the spot.
As mentioned above, if you’re seeking a career in PHP coding, Zend is the major framework companies are asking for. This may also be fuelled by the fact that ecommerce platform Magento utilises Zend as its underlying structure.
For bespoke apps, it’s often difficult to think why you wouldn’t use a framework. However, there may be a few exceptions:
- You want the site to take advantage of skinning/ themes so you can easily develop generic sites, in which case WordPress is a good candidate to use.
- You might not want the hassle of dealing with third-party bugs in frameworks. There may also be too much unwanted automagic behaviour.
The table below shows you some of the features each of the four major frameworks have to help you decide which is the right one for your project:
Frameworks in general provide a solid grounding in creating bespoke web apps from scratch. However, PHP frameworks can often get confused with CMS systems such as Joomla, WordPress or Drupal; they provide a ready made platform for content management which you can also add bespoke features to.
People often ask whether changing from one framework to another is an easy task. In short, migration from one framework or indeed from a CMS system is equivalent to a complete site rewrite. Even though they all employ an MVC architecture, each framework’s interpretation and philosophy is substantially different.
11. Other technologies
All PHP frameworks should never be standalone. Integration with third-party software needs to be taken into consideration. It’s fair to say that the bigger the PHP framework the harder this is to do.
Incorporating JavaScript libraries/frameworks is generally straightforward; it more or less involves the frontend. All the PHP frameworks have helper functions for including JavaScript and CSS files. At the other end of the scale, you can just include the library as a straight <script> tag in the HTML.
PHP frameworks are also equipped to handle many of the common security issues such as XSS (access vulnerability), XSRF (load a malicious page) and SQL injection (steal data). And when it comes to SEO, all the frameworks have structures built in to deal with requirements such as URL re-writing. Note that speed is a factor for SEO and the size of the framework needs to be considered.
Finally, when thinking about cloud computing/ hosting, large frameworks such as Zend or Symfony should be factored in when purchasing servers.
12. Conclusion
In most cases, frameworks bring a helping hand to any project. But as with any tool, how much they can help very much depends on the circumstances.
If your site involves more content, Drupal or WordPress may be a better fit. If you’re building the next Twitter to launch ASAP, CodeIgniter or CakePHP would be good choices. If your environment is corporate, then Zend or Symfony may suit best.
Finally – if you feel you need to create a bespoke PHP framework, get cracking: it’s actually quite fun!
This article first appeared in .net – the world's best-selling magazine for web designers and developers.
Kai Chan is a freelance web developer, has over 16 years experience in creating web apps for corporate brands and loves new startup ideas
Liked this? Read these!
- 50 amazing examples of HTML5
- How to build an app
- The best free web fonts for designers
Thank you for reading 5 articles this month* Join now for unlimited access
Enjoy your first month for just £1 / $1 / €1
*Read 5 free articles per month without a subscription
Join now for unlimited access
Try first month for just £1 / $1 / €1
The Creative Bloq team is made up of a group of design fans, and has changed and evolved since Creative Bloq began back in 2012. The current website team consists of eight full-time members of staff: Editor Georgia Coggan, Deputy Editor Rosie Hilder, Ecommerce Editor Beren Neale, Senior News Editor Daniel Piper, Editor, Digital Art and 3D Ian Dean, Tech Reviews Editor Erlingur Einarsson and Ecommerce Writer Beth Nicholls and Staff Writer Natalie Fear, as well as a roster of freelancers from around the world. The 3D World and ImagineFX magazine teams also pitch in, ensuring that content from 3D World and ImagineFX is represented on Creative Bloq.