0

I'm starting a new bundle. Its goal is to display some statistics arrays and charts. The problem is I don' t know where to transform raw data into usable data in view's arrays and charts. I read lot of articles about keeping the controllers as thin as possible. And as far as I know, repositories are meant to extract data, not transform them.

Where am I supposed to transform my raw data, according to Symfony2 best practices?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
VaN
  • 2,180
  • 4
  • 19
  • 43

2 Answers2

0

it depends on your application but based on what you described looks like you need to define a Service and write all your logic there so your controller would look something like this

$customService = $this->get('my_custom_service');
$data          = $customService->loadMyData();

read more about Services in Symfony: http://symfony.com/doc/current/book/service_container.html

trrrrrrm
  • 11,362
  • 25
  • 85
  • 130
0

Simply create your own, custom service that uses some repository/ies to extract the data and transform it into usable form.

Sample:

// repository

interface MyRepository {
    public function findBySomething($something);
}

class MyRepositoryImpl extends EntityRepository implements MyRepository {
    public function findBySomething($something) {
        return $this->createQueryBuilder('a')
            ->where('a.sth = :sth')
            ->setParameter('std', $something)
            ->getQuery()
            ->getResult();
    }
}

// service

interface MyService {
    public function fetchSomeData();
}

class MyServiceImpl implements MyService {
    /** @var MyRespostiory */
    private $repo;

    public function __construct(MyRepository $repo) {
        $this->repo = $repo;
    }

    public function fetchSomeData() {
        $rawData = $this->repo->findBySomething(123);
        $data = [];

        // do sth

        return $data;
    }
}

// final usage, eg. within a constructor

class MyConstructor extends Controller {
    /** @var MyService */
    private $myService;

    public function __construct(MyService $myService) {
        $this->myService = $myService;
    }

    public function someAction() {
        // you could also get access to the service using $this->get('...')
        $data = $this->myService->fetchSomeData();

        return $this->render('SomeTemplate', [
            'data' => $data
        ]);
    }
}

// service declaration
<service id="myService" class="MyServiceImpl">
    <argument type="service" id="doctrine.repository.my_repository" />
</service>
Crozin
  • 43,890
  • 13
  • 88
  • 135