Reputation: 206
Hi i want to inject a service Class without call her constructor, be cose i havent yet the argument to pass to this constructor class injected.
Exemple:
services:
your.service.name:
class: AppBundle\Services\YourClassName
arguments: ['@doctrine.services.paginator']
doctrine.services.paginator:
class: Doctrine\ORM\Tools\Pagination\Paginator
public: false
return error
Type error: Too few arguments to function Doctrine\ORM\Tools\Pagination\Paginator::__construct(), 0 passed in ... and at least 1 expected
Upvotes: 0
Views: 5098
Reputation: 697
You can use setter injection, which is optional, and not really recommended, but I won't go deep about that.
Example:
<?php
class YourClassName
{
private $paginator;
public function setPaginator(PaginatorInterface $paginator)
{
$this->paginator = $paginator;
}
public function getPaginator()
{
if ($this->paginator instanceof PaginatorInterface) {
return $this->paginator;
}
throw new \RuntimeException('Paginator is not defined');
}
}
Then you can inject your service without specifying paginator as an argument:
services:
your.service.name:
class: AppBundle\Services\YourClassName
and instead inject it in a runtime:
$this->get('your.service.name')->setPaginator($paginator);
In case, if you need inject paginator also with container, you can use calls
argument with service, more in docs.
If you need to get new instance each time you get service from container, you can use shared
argument, more in docs.
Upvotes: 3
Reputation: 732
It's a bit hard to instantiate a class without using the constructor,
PHP documentation says :
PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.
If you want to use the paginator without injecting dependencies, you could follow the doctrine documentation :
Doctrine paginator documentation
Basically you insert use statement in your repository.
use Doctrine\ORM\Tools\Pagination\Paginator;
And then use an object of the Paginator Class with your query :
$qb = $this->CreateQueryBuilder('u');
// ... build your query here...
$qb->getQuery();
$paginator = new Paginator($qb, false);
$count = count($paginator);
return array($paginator, $count); // Process the results in your controller
Hope this helps
Upvotes: 1