Add third party libraries to Symfony 2

Adding libraries that follows the PHP 5.3.+ with namespaces is trivial, but how we can add an old PHP library without namespaces?

For example, if we want to add a library like GeSHi which has an old-style format (without namespaces), we have to do a little trick.

As the Symfony 2 standard says, we have to store all the external libraries into the /vendorfolder. In order to force GeSHi to load following the PSR-0 standard (autoloading standard) we must create the following directory structure: Continue reading

Configuring Symfony 2 for Gaufrette and Amazon S3

We’ve got a really big project that’s being built in Symfony 2. It’s going to be hosted on Amazon Web Services (AWS), so I looked into integrating S3 into our build. The KnpLabsGaufretteBundle seems to be the right choice for the job due to its clean abstraction, but getting it to actually run was a bit trickier than it should have been. Continue reading

Upload files to Amazon S3 with Symfony2 and Gaufrette

Gaufrette, a PHP library, abstracts reading and writing files and allows us to write code independent of the underlying filesystem. In this article we want to store photos on Amazon S3 in a way that we can change the filesystem without changing our code.

Often it can be a little bit tricky to upload files to a web server and things become even more complicated when you want to store the uploaded files on Amazon S3. In this article I am going to explain how you can use Gaufrette to upload photos to S3 from a Symfony2 application. Continue reading

Inject a repository instead of an entity manager

It appears that I didn’t make myself clear while writing about entity managers and manager registries yesterday. People were quick to reply that instead you should inject entity repositories. However, I wasn’t talking about entity repositories here. I was talking about classes that get an EntityManager injected because they want to call persist() or flush(). The point of my previous post was that in those cases you should inject the manager registry, because you don’t know beforehand which entity manager manages the entities you are trying to persist. By injecting a manager registry you also make your code useful in contexts where another Doctrine persistence library is used.

 

However, most classes, especially those close to the business of the application, are not in need of an entitymanager, but of an entity repository. Those classes use an injected entity manager only to retrieve a repository:

use Doctrine\ORM\EntityManager;

class SomeCustomerRelatedClass
{
    private $entityManager;

    public function __construct(EntityManager $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function someMethod()
    {
        $customer = $this
            ->entityManager
            ->getRepository('Acme\CustomerBundle\Entity\Customer')
            ->findOneBy(...);

        ...
    }
}

The Law of Demeter

The entity manager is only injected to retrieve some other object (the repository) on which actually useful methods are called. This is a violation of the Law of Demeter, which requires to only call methods one level deeper than the current level (i.e. we should not go further than calling methods on the injectedEntityManager). This becomes especially problematic when we write unit tests for this class, because we would have to create nested mock objects.

Factory service

When you notice that a class only uses an entity manager to get a repository from it, you’d better refactor it to get the repository itself injected, instead of the entity manager. With Symfony you can define a service for the repository like this:

services:
    acme_customer.customer_repository:
        class: Doctrine\ORM\EntityRepository
        factory_service: doctrine.orm.default_entity_manager
        factory_method: getRepository
        arguments:
            - Acme\CustomerBundle\Entity\Customer

The class is a required value, though it doesn’t really matter here. What matters are the factory_serviceand factory_method keys. They instruct the service container to call the getRepository() method on the entity manager service with the entity class name as the first argument. The result will be returned as the repository service. Read more about service factories in the official documentation of the Dependency Injection component.

Once you have defined such a service for the repository that you need in your class, you can inject the repository service itself, instead of the entity manager. This will help you follow the Law of Demeter, which makes testing easier and will make your code a bit simpler:

use Doctrine\ORM\EntityRepository;

class SomeCustomerRelatedClass
{
    private $customerRepository;

    public function __construct(EntityRepository $customerRepository)
    {
        $this->customerRepository = $customerRepository;
    }

    public function someMethod()
    {
        $customer = $this->customerRepository->findOneBy(...);

        ...
    }
}

Custom repository classes

There are some remaining design issues. The most important one is: the class above is not entirely honest about its dependencies. It does not need just an EntityRepository, it needs the entity repository for Customerentities. So you can make your code much more expressive by making use of custom repository classes. You need to create a repository class which extends EntityRepository and then you need to mention that class in the metadata of your entity:

namespace Acme\CustomerBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * @ORM\Entity(repositoryClass="Acme\CustomerBundle\Entity\CustomerRepository")
 */
class Customer
{
    ...
}

class CustomerRepository extends EntityRepository
{
    ...
}

Now you can inject the custom repository, which makes your intentions much clearer and the code more expressive:

use Acme\CustomerBundle\Entity\CustomerRepository;

class SomeCustomerRelatedClass
{
    private $customerRepository;

    public function __construct(CustomerRepository $customerRepository)
    {
        $this->customerRepository = $customerRepository;
    }

    ...
}

The next step would be to refactor any call to the generic find(), findBy() and findOneBy() methods, including any call that relies on the magic __call() method of the EntityRepository class. Consider this call to the CustomerRepository class:

$this->customerRepository->findBy(array(
    'city' => 'Amsterdam',
    'confirmed' -> true
));

Such a query couples your class to the actual mapping of the Customer entity, because if the mapping changes (e.g. you rename the field confirmed to isConfirmed), the code in this class needs to be modified too. You can easily prevent this coupling by introducing a specific method in your custom repository class:

class CustomerRepository extends EntityRepository
{
    public function findByCity($city, $confirmed)
    {
        return $this->customerRepository->findBy(array(
            'city' => $city,
            'confirmed' => $confirmed
        ));
    }
}

The good thing is that any mapping changes will not ripple through to other parts of the application. They will be limited to the entity class itself and its repository class.

Repository interfaces

One other coupling-related design problem is the fact that the CustomerRepository is being injected, which extends EntityRepository. This couples a class using the CustomerRepository to Doctrine ORM: you would not be able to replace the CustomerRepository with a repository that extendsDoctrine\MongoDB\ODM\DocumentRepository and works with MongoDB documents, because it already extends Doctrine\ORM\EntityRepository.

The solution would be to apply the Dependency Inversion Principle here (the “D” of the SOLID design principles). It tells us that we should depend on abstractions, not on concretions. In this case we depend on aconcrete thing, namely an entity repository. Instead we should depend on an abstract object repository which returns objects, whether they are persisted as documents, entities, or not persisted at all.

So for every entity repository we inject, we need to define an interface, which abstracts the actual database queries. For example:

interface CustomerRepository
{
    /**
     * @param string $city
     * @param boolean $confirmed
     * @return Customer[]
     */
    public function findByCity($city, $confirmed);
}

We don’t promise to return an array, nor an ArrayCollection; we promise to return something traversable (i.e. an array or an object that implements \Traversable) the values of which are instances of Customer.

Now we rename our existing CustomerRepository class to DoctrineORMCustomerRepository orCustomerEntityRepository and we make sure it implements the new repository interface:

class DoctrineORMCustomerRepository extends EntityRepository implements CustomerRepository
{
    public function findByCity($city, $confirmed)
    {
        ...
    }
}

This allows you (or others) to define other customer repositories which don’t extend EntityRepository, but use some other way of persisting and retrieving Customer objects.

You may be tempted to make the CustomerRepository interface extend theObjectRepository interface from the Doctrine Common persistence sub-library, but I’d recommend against it, because it reintroduces coupling to Doctrine.

Something to be aware of: resetting closed entity managers

As Christophe Coevoet pointed out in a comment about a related article by Wojciech Sznapka, there is one disadvantage to immediately injecting repositories in your services. In some situations, especially in long running parallel processes, an entity manager sometimes commits a database transaction which causes an exception to be thrown, which finally causes the entity manager to close itself. The assumption then is that there probably is some discrepancy between the data in the database and the entities that are kept in memory. In order to prevent accidental damage being made to the data persisted in the database, a closed entity manager refuses to perform any new operation to the database, and whatever method you call on it, you will always get this exception:

[Doctrine\ORM\ORMException] The EntityManager is closed.

In these situations, when the entity manager is closed, you can reset the entity manager by callingresetManager() on the ManagerRegistry (e.g. the doctrine service). This will cause the reference to the existing entity manager object to be set to null. The next time an entity manager is requested, a new one will be instantiated, which does not rely on entities currently being kept in memory.

The problem is that repositories that were already injected in services like described above will not be refreshed automatically. They still rely on the closed entity manager. This would be a good case for injectingManagerRegistry instances everywhere. However, since most applications don’t suffer from the “closed entity manager” problem, I would not advise to apply this by default. But it’s good to know when you run into this difficult situation.

Other interesting material: criteria

Traditionally a repository is meant to accept “criteria” objects, based on which actual database queries can be made. I read about this also on Benjamen Eberlei’s blog, but I never used this in practice (I will investigate this option of course). I saw there is also native support for this in Doctrine ORM, by means of the matching()method of the EntityRepository class. Official documentation on this is missing so if you have suggestions, please let me know.

Suggestion: add a save function to your repository

One last suggestion I’d like to point out here (as mentioned by Wojciech Sznapka in a comment on my previous post) is that you can skip injecting any entity manager at all if you add a save() method on your repository, which performs persist() and flush() operation on the entity manager itself:

class DoctrineORMCustomerRepository extends EntityRepository implements CustomerRepository
{
    public function save(Customer $customer)
    {
        $this->_em->persist($customer);
        $this->_em->flush();
    }
}

You rarely need an entity manager for something else, so this really settles most issues.

Copy from http://php-and-symfony.matthiasnoback.nl/2014/05/inject-a-repository-instead-of-an-entity-manager/

Continue reading

Save a Base64 Encoded Canvas image to a png file using PHP

This and the next post will demonstrate how to draw on a canvas and then save the file on a server using PHP. Here is the very simple server side code:

<?php
// requires php5
define(‘UPLOAD_DIR’, ‘images/’);
$img = $_POST[‘img’];
$img = str_replace(‘data:image/png;base64,’, ”, $img);
$img = str_replace(‘ ‘, ‘+’, $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . ‘.png’;
$success = file_put_contents($file, $data);
print $success ? $file : ‘Unable to save the file.’;
?>

The next post will be the slightly more complicated front-end code. This was particularly designed for a Sencha Touch iPad app that will allow people to sign with their finger. It has some flaws, but the basics are pretty reusable and good!

Your result may look something like this:

Copy from http://j-query.blogspot.fr/2011/02/save-base64-encoded-canvas-image-to-png.html
By dbglory Posted in PHP

Stored Procedures in MySQL and PHP

Put simply, a Stored Procedure (“SP”) is a procedure (written in SQL and other control statements) stored in a database which can be called by the database engine and connected programming languages.

In this tutorial, we will see how to create an SP in MySQL and execute it in MySQL server and in PHP.

Note: We are not going to cover the full aspect of the SP here. The official MySQL document should always be the place for reference. Continue reading

By dbglory Posted in PHP

Basic authentication

As the name implies, basic authentication is the simplest method of authentication, and for a long time was the most common authentication method used. However, other methods of authentication have recently passed basic in common usage, due to usability issues that will be discussed in a minute.

How basic authentication works

When a particular resource has been protected using basic authentication, Apache sends a 401 Authentication Requiredheader with the response to the request, in order to notify the client that user credentials must be supplied in order for the resource to be returned as requested. Continue reading

Password protection with Apache but allow from an IP address

I have posted how to password protect a directory and remove password protection from a subdirectorywith Apache and in this post look at how to have a password for all users except those from a defined IP address or set of IP addresses

Basic password protection

Refer to the full post about password protection for all the examples and details, but here’s a quick look at how to add the appropriate lines to an .htaccess file or a <Directory> or <Location> block within the main Apache configuration:

AuthUserFile /path/to/.htpasswd
AuthName "Restricted Access"
AuthType Basic
require user [username] Continue reading 
By dbglory Posted in PHP