Sunday, September 2, 2012

The Treehouse Show

Keep yourself informed

As a web developer or web designer you need to inform yourself about the latest news and tools available. A few weeks ago I found this cool show named The Treehouse Show presented by Nick Pettit and Jason Seifer. 

In the first episode they talk about Responsive Web Design as well as several CSS and JavaScript tools. Also in the first episode they are talking about Twitter Bootstrap

I posted the first episode here, I suggest you to check the others too because I am sure that it will help you as it helped me too! Check their youtube channel, they have a lot of tutorials related to web design and web development.



Monday, July 16, 2012

Start working as a freelance programmer

Workflow

If you want to start working as a freelancer you must know that sometimes you will not have projects to work on and sometimes you will have a lot of bids that were accepted. You should not decline any project that you could complete because if you do a good job then your employee will hire you again for other related jobs.

When you do not have any project in progress do not worry, just bid on projects and use your spare time to learn. An important thing to keep in mind is not to overwhelm yourself with work because only when you are rested you will do a good job.

You should continuously learn something new

IT world is continuously developing, so are the new technologies, principles and practices. You should always keep your knowledge up to date. For example if you use a CMS then you should know that at least once an year a new version is released. You will need to study and learn what new approaches implies the new release. Most of the freelance programmers are working with several languages and libraries. Let's say if you are a developer and you are using PHP, maybe a PHP framework, HTML/CSS is a must, maybe even a CMS and Javascripts's library jQuery then you will need to always learn the new things. 


A good way to learn new approaches to different problems is reading books. Other good learning resources are video tutorials, articles,


Personal skills

English is a must in freelancing, as a freelancer you will need to communicate with clients or other developers, in my experience English is the most spoken language. Another great skill needed is communication, Employee will hire you again if they considered you a nice person.

Prove your employee that you are reliable, do not leave him in the middle of a project just because things get hard. If you do your best then you will win a friend and future collaboration. 


Create a personal website

You should create a personal website where you should put some portfolio items, contact information, maybe a contact form and maybe if you have time write some tutorials about what you are doing(programming, writing, design). Post some links to your profiles on freelancing platforms.


Build trust between you and your employee

First you should be honest, if you can not complete the job then tell him do not abandon the job by not responding to his messages. Clients appreciate honesty!
When you are registered on freelancing websites post relevant information about yourself on your profile. Also you should upload a decent photo with yourself because clients are more comfortable if they see the person to whom they are giving a task or a project. Another thing to keep in mind is to do a good job and to not try to overcharge your clients! All this will build trust between you and your clients, this trust will get you more work. 

Freelancing platforms

Here are some freelancing websites that I tried:
vWorker.com
freelancer.com
A website that is not really a freelancing platform is http://fiverr.com/, however you could browse the website and find out more about it, maybe you could do some work there. I have made some PHP scripts there for some bucks.

Other websites that I did not tried yet are:
http://odesk.com/
http://www.guru.com/
https://www.elance.com/

If you have an advice or something to help new freelancer please post them in your comments. Thank you! 

Thursday, July 5, 2012

Including php files

Let's say that you have some functions that you want to use for a project of yours. If you copy paste the functions in all files where you need then when you want to change the way a function work you need to change it in all places. This changes are a lost of time and you will surely not modify it in all files so bugs may appear. The solution is to include php files using include and require methods that PHP provides us.

Using include

You can include a file like this:
include "functions.php"
Using this statement requires that the file functions.php must be in the same folder with the file in which you are including your functions. You can use relative or full path to the file like this:

include "usr/local/apache/htdocs/includes/functions.php"
For Unix/Linux/Mac path

For Windows the include statement might look like this:
include "c:\phpfunctions\functions.php"

The problem with include is that every time the PHP processor finds an include statement is that it will load the file in again. This takes up more memory than is necessary and is slow and inefficient. The other problem is that loading the file again will make functions to be redefined, which is not allowed, and will generate an error message.

Using include_once

If you are using include_once then the processor will check if the file is not already loaded and it will load it if it is not loaded. You can use it like this:
include_once "functions.php"

The problems with include and include_once is that if the file does not exist then the command will simply get ignored. Maybe some of those functions are needed for the website to work then you will get a lot of errors, maybe some errors like function not found. The solution is the require command.

Using require

require "functions.php"
Using require instead of include will return an error and halt the program execution if it cannot locate the requested file. This will help you if you misplaced a file or you got the file name wrong. But the story is the same, require will reload the file each time, the problems of this matter are the same as when using include command. The final and best solution is require_once command.

Using require_once

require_once "functions.php"
Like include_once this will only ever load in a single copy of the file, no matter how often that file is required. But, unlike include, it will also generate an error if it can not find the requested file.


Reference:

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!

Monday, May 21, 2012

Installing Sonata Bundle Error

If you get the next error when using Sonata Admin Bundle you should use the Sonata Admin Bundle 2.0 branch.

Fatal error: Declaration of Sonata\AdminBundle\Form\Extension\Field\Type\FormTypeFieldExtension::getDefaultOptions() must be compatible with that of Symfony\Component\Form\FormTypeExtensionInterface::getDefaultOptions() in /var/www/pulpower.spotymedia.com/vendor/bundles/Sonata/AdminBundle/Form/Extension/Field/Type/FormTypeFieldExtension.php on line 186

 Clear the deps file and copy the next code

[SonataAdminBundle]
    git=git://github.com/sonata-project/SonataAdminBundle.git
    target=/bundles/Sonata/AdminBundle
    version=origin/2.0

run the command php bin/vendors install -reinstall

Now everything should work.

https://github.com/sonata-project/SonataAdminBundle/issues/679

How to Get the Most Out of Studying

Here is a playlist of videos made by a professor of physiology at Samford University in which he is explaining "How to get the most out of studying". I think this videos are very useful for everyone who is self learning or is a student.

Sunday, May 20, 2012

Symfony2 assets:install error

If you get the next error when running php app/console assets:install --symlink ./web:

  Warning: unlink(./web/bundles/framework): Permission denied in C:\wamp\www\project
\vendor\symfony\src\Symfony\Component\HttpKernel\Util\Filesystem.php line 100

Then delete folders in project/web/bundles/ then run the command and it should work.

Installing SonataAdminBundle Error

If you get the next error when installing SonataAlbumBundle:
The child node "default_contexts" at path "sonata_block" must be configured.

Then you should include this code in your app/config/config.yml file
 # app/config/config.yml
sonata_block:
    default_contexts: [cms]
    blocks:
        sonata.admin.block.admin_list:
            contexts:   [admin]

        #sonata.admin_doctrine_orm.block.audit:
        #    contexts:   [admin]

        sonata.block.service.text:
        sonata.block.service.action:
        sonata.block.service.rss:

        # Some specific block from the SonataMediaBundle
        #sonata.media.block.media:
        #sonata.media.block.gallery:
        #sonata.media.block.feature_media:

Wednesday, May 16, 2012

Start learning Symfony2 help

You want to learn Symfony2? Here check the next list of websites that I found and learned from:
  1. http://tutorial.symblog.co.uk/  Darren Rees wrote a great tutorial for creating a blog in Symfony2. This tutorial helped me to get started with Symfony2, I hope it will help you too.
  2. You should read all you can from the official website http://symfony.com/ because the documentation is great and there is a lot of stuff that will help you get started. Also there are some very interesting videos about Symfony2 at http://symfony.com/videos
  3.  This presentation http://www.youtube.com/watch?v=VuNFof59A7M made by Fabien Potencier helped me a lot, because he explains in detail how some of the components work.
  4. Symfony2 the maturity of PHP frameworks in this video Stefan Koopmanschap is explaining a lot of interesting stuff about Symfony2 that will help you understand about the framework. 
  5. http://www.ens.ro/2012/03/21/jobeet-tutorial-with-symfony2/ A kind sir made a Jobeet tutorial with Symfony2

I hope this will help you! If you know other good learning resources please post them here. Thank you!

Monday, May 7, 2012

How to check if Entity is in an array collection of another Entity

 Check if $friend is in the friends array collection of the user
$user->getFriends()->contains($friend); 

if $friend is in the array collection  method returns true otherwise it returns false

Sunday, May 6, 2012

Symfony2 Security component. How to get the user who is logged-in?

If you are using Symfony2(version 2.0.12 2012-03-19 ) and using Security component then you can get the logged in user like this:


$user = $this->container->get('security.context')->getToken()->getUser();

Symfony2 many-to-many self referencing relation using Doctrine2

Symfony2 many-to-many self referencing relation using Doctrine2

 Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::serialize() must return a string or NULL

I created this blog because I wanted to help others who are self learners like me. I spent few hours to figure out why I was getting the next error when playing with Symfony2.
Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::serialize() must return a string or NULL

I had an User entity a many to many self referencing relation. I still did not find out why I was getting the error but I found out here a way to get rid of the error. I just had to add the __sleep method for the user entity like this:

/**
 * @ORM\Entity(repositoryClass="Acme\DemoBundle\Repository\UserRepository")
 * @ORM\Table(name="users")
 * @ORM\HasLifecycleCallbacks()
 */

 class User
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
    ..................
    public function __sleep()
    {
        return array('id');
    }
}

I hope this helped someone who got the same error as I did. If you have a better solution please post it here.