Search code examples
phpsymfonypropelsymfony-2.3

Autoload a simple DAO in Symfony2+Propel


I've been working on a project and I decided it'd be a good idea to have some sort of, like, DAO, but simplified.

Basically, the only thing I want from it (right now, at least) is to fetch me objects by model name and id. I wrote this very simple piece of code:

class DAO {

  public static function get($className,$id) {
    $queryName = $className."Query";
    if (!class_exists($className) || !class_exists($queryName)) {
        return false;
    }       

    $q = $queryName::create()->filterByID($id)->find();
    return $q;

}

}

However, I found myself stuck with the implementation. I guess I need to somehow autoload it so that it'll be able to check for the existence of the classes and so that I could use it anywhere inside my app, but I don't know how. Can anyone help me out? Or if there's a better way to do that, I'll appreciate any input.


Solution

  • What you're looking for is a Service.

    Definition from the documentation:

    Put simply, a Service is any PHP object that performs some sort of "global" task. It's a purposefully-generic name used in computer science to describe an object that's created for a specific purpose (e.g. delivering emails). Each service is used throughout your application whenever you need the specific functionality it provides.

    Defining your class as a service is as simple as this:

    app/config/config.yml

    ...
    services:
        my_dao:
            class:        Your\Bundle\DAO
    ...
    

    Now you can access DAO in your controllers doing something like this:

    $dao = $this->get('my_dao');
    

    When you make this call, the Service Container will create an instance of your class and return it. There will always be at most one instance (singleton) and if it's never called, it won't even be instantiated.

    I recommend reading the documentation.

    Opinion

    It seems like you're having trouble adapting to the Symfony way.

    If you take a look at The Book you'll see that the Entity Manager in conjunction with your entity's Repository handle most of what DAO's traditionally did. In other words, there's really no need for your DAO class.

    For example, fetching any object by id is as easy as:

    $om->getRepository('YourBundle:YourModel')->find($id);
    

    Anyway, if you're particularly fond of that approach, you may want to try this project.