Friday, June 22, 2012

Why use a PHP framework?

There are several reasons to use a framework instead not using one. The framework that you are using can be one that is open source or your company/team developed for future projects. Learning how to use a PHP framework(or any other framework developed for other languages) can take time depending on multiple factors like documentation, community, practices and patterns that it uses. But it will worth your time because when developing web applications using that framework it will be faster than not using one. 

For example Codeigniter is a lightweight framework that it is easily to use and learn, I mean really easy to learn it. You can start developing a website after a few hours you have downloaded it. But if you have to work on a large project then you should use for example Zend or Symfony2 because these frameworks have more components available to help you with different tasks.

Easier to understand someone else code

 Firstly if you using a framework then other developers who uses it will understand better your code. If developers understand better the code then they will easily extend, fix bugs or use what you wrote. Let's say that you work at a small company in a team of web developers and one of your team member gets married then he has no time to finish the project on which he was working on. Another team member will easily continue his work if he uses the same framework and if the team has a certain coding standards.

If you have some experience with a framework then you will get a job easier because a lot of companies use at least one framework. The most popular frameworks are Symfony2, Zend, Codeigniter, CakePHP. Here is a comparison.

Built in classes that help you

The second advantage of a framework is that you can reuse classes that helps you to get your job done faster. For example the framework can have a database layer that is easier to use for connecting to a database, maybe the framework has a class that helps you to write queries without writing any sql. Of course that in larger projects you must know how to write complicated queries.

Another example is Zend, this framework has a lot of modules that help you to work with different APIs. Zend has a module that helps you to work with Amazon Service. Here is a piece of code example:

$amazon = new Zend_Service_Amazon('AMAZON_API_KEY', 'US',  
'AMAZON_SECRET_KEY');
$results = $amazon->itemSearch(array(
    'SearchIndex' => 'Books',
    'Keywords' => 'php',
    'AssociateTag' => 'yourtaghere'
));

Your web application would be more secure

Another advantage is that a lot of PHP frameworks have built-in security. I am not saying that you should leave the framework to take care of all the ways that someone could break your website but your web application would be more secure if you are using a framework.

Build in caching

Most frameworks have build in caching components that will make your web application faster. This components give you the power to control caching in different ways like timing and other things. Here is an article about Symfony2 caching component.

Separating your logic in your web application

For example if you are using a MVC framework and you are separating the logic of application in the three major parts: views, controllers and models then it will be faster to develop, test it, refactor it and understand it. The views should not contain any logic, it should only present data to the user. The controller must receive a request and return an response. And most importantly the models should contain your logic of the application and your database queries. If do not organize your files and your code properly then your project will become a mess and it will be hard to debug it, to extend it and to reuse that code. It will become a spaghetti code!

Conclusion

Learning a php framework can take time depending on which you are learning but the productivity will grow. Frameworks have a lot of components that will ease your work. Inevitably you will learn to separate your files and code in a way that makes sense to you and the others who use the same framework. Almost all PHP frameworks are Object oriented so all of them use the best OOP Patterns to solve common problems. If you want to start building your own MVC framework then you should follow this tutorials.


Saturday, June 16, 2012

Introduction to Object-oriented programming with PHP

I found a great slideshow consisting of 122 slides in which Marcus Börger made an introduction to Object-oriented programming with PHP. The presentation was made at a PHP Conference in Quebec in 2007 and the author pointed out the next topics:
  1. What is OOP?
  2. PHP and OOP
  3. Exceptions
  4. Iterators
  5. Reflection
  6. Patterns
 I think this will help you understand better the Object Oriented programming in PHP even if the presentation was made in 2007.

Thursday, June 14, 2012

20 advices when starting to learn PHP

Here is a great article to read if you are just starting to learn php. The presented advices are:

  1.  Program as often as you possibly can
  2. Get familiar with the PHP manual
  3. Take advantages of the huge online PHP Community
  4. Don't put off the best practices for later
  5. Don't put off the best practices for later(to be sure you saw this)
  6. Make code self-documenting
  7. Add a comment to anything you had to think about
  8. Learn Docblock and use it!
  9. Don't be too hardcore to use an IDE
  10. Group common code into functions
  11. Group related functions into classes
  12. Use constants, not globals
  13. Don't be afraid to use includes
  14. Don't obsess over performance
  15. Avoid Marrying HTML to your scripts
  16. Try to use at least one unfamiliar concept in every project
  17. Don't be too proud to change
  18. Validate
  19. Whitelists instead of blacklists
  20. Learn to count like a computer
Please read the article to understand better each advice. Thank you Jason Lengstorf at http://net.tutsplus.com .

Monday, June 11, 2012

Sonata AdminBundle: How to create a custom field

I wanted to create a custom field that is not in the database for the listFields so I searched the web how do it. Here is how I have done it:


class Entity 
{
    ...
    //custom getter
    public function getFullName()
    {
        return $this->getFirstName() . ' ' . $this->getLastName();
    }
}


In your EntityAdmin:

 protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
           ->add('fullName', 'doctrine_orm_string')
            ->add('_action', 'actions', array(
                'actions' => array(
                    'view' => array(),
                    'edit' => array(),
                    'delete' => array(),
                )
            ))
        ;
    }

Sunday, June 10, 2012

Sonata Admin Bundle error:configureShowFields

If you get this two errors:
[2/2] FileLoaderLoadException: Cannot import resource "C:\wamp\www\project\app/config\." from "C:\wamp\www\project\app/config\routing.yml".  -+

[1/2] ErrorException: Runtime Notice: Declaration of Company\NameBundle\Admin\EntityAdmin::configureShowFields() should be compatible with that of Sonata\AdminBundle\Admin\Admin::configureShowFields() in C:\wamp\www\havefun\src\Company\NameBundle\Admin\EntityAdmin.php line 84  -

Check if you included the ShowMapper class like this:
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Show\ShowMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Validator\ErrorElement;
use Sonata\AdminBundle\Form\FormMapper;

protected function configureShowFields(ShowMapper $showMapper)
    {
        $showMapper
            ->add('name')
            ->add('email')
        ;
    }

Saturday, June 9, 2012

SonataAdminBundle weird breadcrumbs

If you installed SonataAdminBundle and your breadcrumbs look like this 0/1/ then the solution to this problem is to reinstall the KnpMenuBundle, but the 1.1.0 version, you can find it on git . Add this to your deps file:
[MenuBundle]
git=https://github.com/KnpLabs/KnpMenuBundle.git
target=/bundles/Knp/Bundle/MenuBundle
version=v1.1.0

[KnpMenu]
git=https://github.com/KnpLabs/KnpMenu.git
target=/knp/menu
version=v1.1.1
  
But before running the command  php bin/vendors install --reinstall  make sure you comment the
'Knp\Menu'   => __DIR__.'/../vendor/knp/menu/src',
    'Knp\Bundle' => __DIR__.'/../vendor/bundles',

in the app/autoload.php file

and comment  the
new Knp\Bundle\MenuBundle\KnpMenuBundle(),

line in the app/AppKernel.php file

Also you might have to comment the:
   lines of code in app/config
      sonata_admin:
    title:      HungryCoders
    title_logo: bundles/sonataadmin/logo_title.png
    templates:
        # default global templates
        layout:  SonataAdminBundle::standard_layout.html.twig
        ajax:    SonataAdminBundle::ajax_layout.html.twig

        # default actions templates, should extend a global templates
        list:    SonataAdminBundle:CRUD:list.html.twig
        show:    SonataAdminBundle:CRUD:show.html.twig
        edit:    SonataAdminBundle:CRUD:edit.html.twig
    dashboard:
        blocks:
            # display a dashboard block
            - { position: left, type: sonata.admin.block.admin_list }

...


services:           
    sonata.admin.product:
        class: Demo\TestBundle\Admin\ProductAdmin
        tags:
            - { name: sonata.admin, manager_type: orm, group: demo, label: Products }
        arguments: [null, Demo\TestBundle\Entity\Product, DemoTestBundle:ProductAdmin]

Now you can run the command to install the vendors, and UnComment the code in app/autoload.php, app/AppKernel.php and app/config/config.yml. Now your breadcrumb should look good.

Monday, June 4, 2012

Event Listener Example

Here is an event listener example. I made a little game using Symfony2 framework and I needed to check if the user chose a hero(character) to play before trying to make some actions like view inventory etc.
src/HungryCoders/HeroGameBundle/EventListener/BeforeControllerListener.php:
<?php
namespace HungryCoders\HeroGameBundle\EventListener;

use Symfony\Component\HttpKernel\Event\FilterControllerEvent;

class BeforeControllerListener
{
  
    protected $session;
    protected $resolver;
  
  
    public function __construct($session, $resolver)
    {
        $this->session = $session;
        $this->resolver = $resolver;
    }
  
    /**
     * This is used to check if the user that wants to access some hero game controller
     * chose a hero to play with
     */
    public function onKernelController(FilterControllerEvent $event)
    {
        $controller = $event->getController();
      

        if (!is_array($controller)) {
            // not a object but a different kind of callable. Do nothing
            return;
        }
        $controller = $event->getController();
        $controllerObject = $controller[0];
      
     
        if ($controllerObject instanceOf \HungryCoders\HeroGameBundle\Controller\BattleController
        ||  $controllerObject instanceOf \HungryCoders\HeroGameBundle\Controller\HeroController
        ||  $controllerObject instanceOf \HungryCoders\HeroGameBundle\Controller\InventoryController
        ||  $controllerObject instanceOf \HungryCoders\HeroGameBundle\Controller\TownController
        )
        {
            if ($this->session->get('heroGameHeroId') === null) {
              
                $this->session->setFlash('heroGame.mustChooseAHero', 'You must choose a hero to play');
              
                //a way to create a new response without any redirect just create a response using a controller action
                $request = new \Symfony\Component\HttpFoundation\Request();
                $request->attributes->set('_controller', 'HungryCodersHeroGameBundle:HeroAccess:dashboard');
                $event->setController($this->resolver->getController($request));
            }
        }
    }
}


src/HungryCoders/HeroGameBundle/Resources/config/services.yml
parameters:
    heroGame.battle.maxRounds: 5
    heroGame.attack.rangeLevels: 5

services:
    beforeController.listener:
        class: HungryCoders\HeroGameBundle\EventListener\BeforeControllerListener
        arguments: [ @session, @controller_resolver]
        tags:
            - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }

Great PHP OOP video tutorials

If you want learn about PHP Object Oriented Programming than I strongly suggest to watch these video tutorials at http://jream.com/learning/videos/php-oop . After you watched them if you want to learn about MVC framework you can start making your own framwork  by following the video tutorials that are available at the same url. I hope this helped you!

Twitter Bootstrap Quickstart

Today I found a great video tutorial on how to get started with Twitter Bootstrap. This is not related to Twitter API, Twitter Bootstrap is a cool HTML, CSS, and JavaScript application that helps you setup a site in minutes. This is a quick example of a few of it's features, you can get it here: http://twitter.github.com/bootstrap/
I am planning on using it on future frontend work on any projects that I can. Thank you http://jream.com/

What is Symfony2?

I found a great article wrote by Fabien Potencier on his website the topics that he reached are:
  1. What is Symfony2?
  2. Is Symfony2 an MVC framework?
  3. Why does it matter?
  4. Why Symfony2
  5. The Symfony2 Components
I really encourage you to read his post! Thank you Fabien Potencier!