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

Remove a Submodule within git

For many git-based projects, submodules are useful in avoiding duplicate work and easing utility library updates.  There are times, however, when a submodule needs to be removed from a project.  Submodules aren’t removed with git rm submoduledir, they must be removed in a more tedious, manual fashion.  There are many unclear explanations of how to remove a submodule but I found one on Stack Overflow that’s concise, so I thought I’d share it.  The steps are as follows: 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

Using Cassandra on Mac OSX

I posted some time ago about installing Cassandra on Mac OSX. Admittedly I generally use Linux when dealing with Cassandra but have recently been using it on Mac OSX again so here are some tips when working with Cassandra on ac OSX.

Install it with homebrew

It’s easy! The only reason for not using homebrew is if you want a specific version. I have an old blog post on installing it with homebrew here: install Cassandra on Mac OSX. If you want 1.2 rather than 2.0 read below first.

Continue reading

How do I set a system-wide proxy in Lubuntu (or LXDE)?

System-wide proxies in Lubuntu or LXDE must be set via environment variables

Lubuntu uses the lightweight LXDE desktop environment which does not contain a graphical settings tool to set systemwide proxies (unlike the default Ubuntu desktop environment, Unity).

The proxies must therefore be set via configuration files. This is a relatively simple procedure, and screenshots of the editor are provided to assist you.

 

1. Set up the proxy/proxies for most programs

  • Open the /etc/environment file with gksudo leafpad (or your favorite editor). This file stores the system-wide variables initialized upon boot.
  • Add the following lines, modifying appropriately. You must duplicate in both upper-case and lower-case because (unfortunately) some programs only look for one or the other:
    http_proxy=http://myproxy.server.com:8080/
    https_proxy=http://myproxy.server.com:8080/
    ftp_proxy=http://myproxy.server.com:8080/
    no_proxy="localhost,127.0.0.1,localaddress,.localdomain.com"
    HTTP_PROXY=http://myproxy.server.com:8080/
    HTTPS_PROXY=http://myproxy.server.com:8080/
    FTP_PROXY=http://myproxy.server.com:8080/
    NO_PROXY="localhost,127.0.0.1,localaddress,.localdomain.com"
  • Screenshot: after running gksudo leafpad /etc/environment:

    enter image description here

    2. Then, set up the proxies for apt-get and Update Manager

  • These programs will not obey the environment variables. Create a file called 95proxies in /etc/apt/apt.conf.d/, and include the following:
    Acquire::http::proxy "http://myproxy.server.com:8080/";
    Acquire::ftp::proxy "ftp://myproxy.server.com:8080/";
    Acquire::https::proxy "https://myproxy.server.com:8080/";
  • Screenshot: after running gksudo leafpad /etc/apt/apt.conf.d/95proxies:

    enter image description here

3. Logout and Reboot

Finally, logout and reboot to make sure the changes take effect.

Copy from http://www.techques.com/question/24-155459/How-do-I-set-a-system-wide-proxy-in-Lubuntu-%28or-LXDE%29

 

By dbglory Posted in Linux