Zend Framework 2 : Error & Exception Handling

Hello everyone, today I am going to share one problem I faced, when I was developing my first project with Zend Framework 2. The issue was with defining and managing error, exceptions. In the front-end, it was displaying errors/exceptions to the user, rather filing it into any file. It was too awkward for user to see the error message as kind of paragraph in the front-end :D.

So, that time, I thought of logging those errors/exceptions in a log file, for further check and fix for the issue, as we always do with any other framework/normal PHP projects. I searched for the native solution, it is present or not in the same Framework. I found the manual (though now-a-days we can find a lot of blogs/tutorials for solving error logging issue), where some logging code has been written, and which I thought would definitely help me to reach my goal.

So, what I did was – I just gone through the manual for error logging once, and believe me, I didn’t understand even 50% of the concept 😀 :D. That’s why I decided myself to keep patience and go through the same manual once again or twice.

Hmmm… after reading 3 more times, I got some points and I thought of using it in the code. Then, I checked and analyzed what should be the best position to use the logger code, so that it would help me as extent and I should not have to write the same code again and again.

So, here I am going to explain what attempt I had taken that time and it was successful also. Let’s check step by step process, of adding the logger for errors/exception.

1st Step
First attach to the dispatch error event inside Module.php (say in Application folder).

public function onBootstrap(MvcEvent $e)
    // other config code

    $sm = $e->getApplication()->getServiceManager();
    $sharedManager = $e->getApplication()->getEventManager()->getSharedManager();

    $sharedManager->attach('Zend\Mvc\Application', 'dispatch.error',
        function($e) use ($sm) {
            if ($e->getParam('exception')) {
                return false;

2nd Step
Create service.config.php file (say Application/config/service.config.php).

return array(
    'factories' => array(
        // other config code ,
        '\Zend\Log\Logger' => function($sm){
            $logger = new Zend\Log\Logger;
            $writer = new Zend\Log\Writer\Stream('./data/logs/' . date('Y-m-d') . '-error.log');

            return $logger;

Now, it’s done. The call anyway will go through bootstrap method and will log the error if any into one file. The path we used above for creating the log is inside ‘data/logs/’ directory. Do you really find it useful? 🙂 If yes, then please like and add some comments, if you want.

Thanks 🙂 and will be happy to listen from you 🙂 :).


Install Zend Framework 2 on Windows OS !!!

As many of us know about ZF2 (Zend Framework 2), it is an open source, object oriented Framework designed for developing web applications and services using PHP 5.3+.

So, in this post we will go through the installation process for ZF2 Framework with a skeleton application so that it will be easier for the developer to continue developing the application directly :).

We will go through just simple 4 steps and then we will be done with the installation.

Step 1 :-
We can install ZF2 skeleton application in 2 different ways.

Case 1 :-

Go to here and click the zip button to download. Unzip this file into the directory where you keep all your vhosts (in this case, I used D:/projects/) and rename the folder to ZendSkeletonApplication.

Case 2:

Install GIT Bash if you have not installed yet. Installing GIT is easy to do. Go to http://git-scm.com ➡ Downloads ➡ Select OS ➡ Save File ➡ Run ➡ Accept all and install it.

Open GIT bash and open the folder where you keep all your vhosts or where you want to create the Project (in this case, I used D:/projects/) and run this command –

git clone git://github.com/zendframework/ZendSkeletonApplication.git

After this, one folder will be created on your specified path named as ZendSkeletonApplication.

Step 2 :-
Open GIT Bash and go to ZendSkeletonApplication folder using

cd D:/projects/ZendSkeletonApplication

Then run the following command

E:/xampp/php/php.exe composer.phar self-update

Then after executing the above command, run the below command

E:/xampp/php/php.exe composer.phar install

Note: Here in my case, I have my xampp folder inside E:/ drive.

Step 3 :-
Add the following in httpd-vhosts.conf (E:\xampp\apache\conf\extra\httpd-vhosts.conf) file. After adding the below lines, restart your xampp.

<VirtualHost *:80>
    ServerName http://zend.localhost.com
    ServerAlias zend.localhost.com
    DocumentRoot "D:\projects\ZendSkeletonApplication\public"
    SetEnv APPLICATION_ENV "development"
    <Directory "D:\projects\ZendSkeletonApplication\public">
        DirectoryIndex index.php
        AllowOverride All
        Order allow,deny
        Allow from all

Step 4 :-
Finally, add the following in your host file (C:\Windows\System32\drivers\etc\host).


😎 great !!! Now, everything is set and ready to use. Browse http://zend.localhost.com and you will get the default skeleton application page :eek:.

Screen Shot 2014-10-06 at 6.47.59 pm

If you are finding the page like above, while browsing http://zend.localhost.com, then 😎 :D, we are done now (clap).

Thanks 🙂 and will be happy to listen from you 🙂 :).

Why to use Framework in PHP!!

The word FRAMEWORK is the combination of two words i.e. FRAME and WORK. It means, one FRAME has already been designed and developer has to WORK on that FRAME to meet his/her project requirements. It’s just a tool, which helps developer to code better and faster.

In computer language, a Framework is an universal, reusable software platform to develop software applications, products and solutions. In other words, we can say it is some kind of library, a piece of software, which provide web developers with code base and consistent standardized ways of creating web applications.

Back when PHP and other technology started, developers were writing their own custom code for each functionality. After then, some people realized that, writing the same code every time, in every page, not reusing it extensively, plain PHP is not so effective.

Afterwards, as the PHP object model developed (especially with the launch of PHP 5), framework development really came into action and became so popular.

So, lets not stretch this topic as chew gum 😀 and let’s check what are the key benefits of using a Framework, especially in PHP.

Organizing Code and File :-
When you setup a PHP Framework, it already has a certain folder structure. Most of the Framework, use MVC (Model-View-Controller) guideline or structure for managing the code. MVC pattern allows to separate business logics and presentation layer of your website, making its structure consistent and maintainable. It is expected from you to follow the same standards and keep everything organized in a certain way. Once you get used to this model, you will never want to go back.

The MVC Pattern :-
The Popular PHP frameworks like CakePHP, CodeIgniter, Zend Framework , Symfony follows Model View Controller(MVC) design pattern which separates business logic from user interface making the code cleaner and extensible. The way the MVC Pattern applies to PHP applications:

  • Models represent your data structures, usually by interfacing with the database.
  • Views contain page templates and output.
  • Controllers handle page requests and bind everything together.

Enforcing of Good Coding Standards :-
Another effect of using Framework is maintaining coding standard in an efficient manner. Coding conventions are a set of guidelines for a specific programming language that recommend programming style, practices and methods for each aspect of a piece program written in this language. Using Framework makes it so much easier to code as you should.

Utilities and Libraries :-
PHP is a great language for web development and provides countless number of tools and libraries. As everybody can guess, these frameworks contains a lot of libraries to make your job easier. All top PHP frameworks come with certain Libraries and Helpers, that help you with:

  • Form Validation
  • Caching Mechanism
  • Input/Output Filtering
  • Data Handle With JSON
  • Database Abstraction
  • Session and Cookie Handling
  • Email, Calendar, Pagination etc…

Less Code & Faster Development :-
These MVC framework will really helps you to develop the project rapidly, if you know one framework well then you’ll never worry about the project deadline. You will write less code, which means less time spent typing. You will not have to chase down 3rd party libraries all the time for every new project because most of them will come with the default framework install. While working on a large project in a team, these MVC PHP framework will be a great tool for development as you can assign a developer to develop MVC part of a module for a developer and integration will be quite easy of these developed module at final level. Also, since you are being more organized, it will be much faster to chase down bugs, maintain code, and make changes to existing code.

Community Support :-
All popular PHP Frameworks have great active communities behind them. There is no lack of support from the community, the documentation, and the developers. If you have any questions or need any clarifications, a quick search with the right keywords should almost always give you relevant results. If not, there’s still the message boards, mailing Lists, the official and unofficial forums or the unofficial IRC channel.

Security :-
With a framework, most of the work for code security can be done for you automatically. For example:

  • Central Authentication
  • Any value passed to database object gets filtered against SQL injection attacks
  • Central input validation and filtering
  • All html generating functions, such as form helpers and url helpers filter the output automatically
  • Cross Site Request Forgery (CSRF) Protection
  • Session Management Security
  • Cross Site Scripting (XSS) Protection
  • Encrypting cookies automatically is only a matter of changing a config option and lot more…

Performance Tools :-
Framework tools are utility module for maintaining modular application. You can actually gain perCode generation make developers life easier by creating files and default content automatically so you don’t have to do the same thing again. Framework come with tools that help you to do caching, benchmarks, profiling etc… Modern frameworks are also great with dynamic loading, as they load code only as needed. Lazy loading concept is also there, to make the web page ready, till the time content is ready. Different page requests can load different amount of library code based on what needs to be used.

Simplified and Pretty URLs :-
Most Framework use a bit of mod_rewrite magic to ensure, your URLS are always clean and accessible. Apache handles requests to a particular URL, and (hidden to the client) returns this URL to /index.php as a GET string. The index page instantiates your main framework object. Accessible URLS also help with SEO. URLs are great for below reasons:

  • They look prettier
  • They are easier to remember
  • They help you save filespace on pages which have many links
  • They are easier to link to, both for you and for other webbies
  • They help cut down on typos because there is less confusion about what exactly to write and type

Efficiently Access Database :-
Framework provides the way to access database in an object-oriented way. Instead of directly interacting with the database using SQL queries, you can use any Object-Relational Mapping (ORM) model to manage the structure and relationships between your data. With ORM model, you can map your database table to a PHP class and a row from that table is mapped to an instance of that class.

Conclusion :-
You might not opt for using PHP Framework or using a Framework may or may not be the best choice for you. But, if we are believing with the word “Performance Really Matters”, then we can try for any popular PHP Framework, and that will be even easier and robust way to develop applications. Frameworks are cool and easy, and we can’t tell what tomorrow is going to bring. I hope this blog will help you to understand what are the advantages of using a Framework and will value Developers.

After reading the above post, are we still thinking, whether to use Framework or not !!! 😐 😮 😦

But, if we got the points and benefits of Framework, then 😎 ;-), we are way to go :). Hope you will like this post and will use Framework, if not till now :mrgreen:.

Thanks 🙂 and will be happy to listen from you 🙂 :).