Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a repository outside of a controller in Symfony2

I am currently using a function to get my repositories like so:

public function getRepositories()
{
    // Tasks
    $tasks = $this->getDoctrine()
        ->getRepository('Model:Task');

    // Task Info
    $taskInfos = $this->getDoctrine()
        ->getRepository('Model:TaskInfo');


    return array(
        'tasks'             => $tasks,
        'taskInfos'         => $taskInfos,
    );
}

So in my controller actions, I can just call some SQL like this:

$repositories = $this->getRepositories();
$task = $repositories['tasks']->findOneById($id);

But now that I have a few controllers, I've noticed that I'm copying that same getRepositories() function into each which is not good as it's replicating the code repeatedly.

What I want is to have like a helper class, and this could be one of the functions in that.

But how do I do this, given the helper class won't be a controller and there for $this->getDoctrine() obviously wouldn't work?

Thanks

like image 288
b85411 Avatar asked May 07 '14 02:05

b85411


2 Answers

You don't really gain anything with the code you want to write. A better practice would be to make a repository class for each entity, which has entity manager injected. You could also define another abstract repository service which those entity services will extend. I do it that way in my applications and I found it really useful, because I can add own functions to the repository I am using.

I can do something like this in controller:

$this->getTaskRepository->findOneById(1);
$this->getTaskRepository->getSomeTasks(); // executes a query with query builder
like image 40
tomazahlin Avatar answered Sep 23 '22 20:09

tomazahlin


You can use services (http://symfony.com/doc/current/book/service_container.html) and inject doctrine.

services:
    my.helper.class:
        class: Acme\MyBundle\Helper\MyHelper
        arguments: [ @doctrine.orm.entity_manager ]

<?php

namespace Acme\MyBundle\Helper;

use Doctrine\ORM\EntityManager;

class MyHelper
{ 
    protected $manager;

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

    public function getRepositories()
    {
        $tasks = $this->manager->getRepository('Model:Task');
        $taskInfos = $this->manager->getRepository('Model:TaskInfo');

       return array(tasks, taskInfos);
    }
}

That being said, I do not really understand the purpose of this in your situation as controllers are meant to get data and return it.

You are not duplicating logic.

It seems too much, the entity manager is already a helper in that way.

like image 149
LBridge Avatar answered Sep 23 '22 20:09

LBridge