问题
I am trying to use DataTablesBundle in Symfony 4.2.
There is very good manual and starter however it is used with extends Controller class. But I am trying to use it with AbstractController class.
So I have such issue:
Service "
Omines\DataTablesBundle\DataTableFactory" not found: even though it exists in the app's container, the container inside "App\Controller\StaffController" is a smaller service locator that only knows about the "doctrine", "form.factory", "http_kernel", "parameter_bag", "request_stack", "router", "security.authorization_checker", "security.csrf.token_manager", "security.token_storage", "serializer", "session" and "twig" services. Try using dependency injection instead
I have found a solution however I have just started with Symfony so I haven't really understood what it is about:
https://github.com/omines/datatables-bundle/commit/cd9b93eac9ef4fd3c1459305c71ca6e2ac0c444e
If using
AbstractControllerinstead, which is currently recommended practice, ensure you subscribe to theDataTableFactoryservice yourself. Alternatively you can bypass the convenience trait and inject the service via regular constructor injection
How to subscribe to the DataTableFactory service?
And what does the alternative "bypass the convenience trait and inject the service" mean?
回答1:
I don't know how to subscribe to a service, but here is how to inject it.
Add a constructor to your controller and inject the DataTableFactory:
//use Omines\DataTablesBundle\DataTableFactory;
private $factory;
public function __construct(
DataTableFactory $factory
) {
$this->factory = $factory;
}
/**
* Creates and returns a basic DataTable instance.
*
* @param array $options Options to be passed
* @return DataTable
*/
protected function createDataTable(array $options = [])
{
return $this->factory->create($options);
}
/**
* Creates and returns a DataTable based upon a registered DataTableType or an FQCN.
*
* @param string $type FQCN or service name
* @param array $typeOptions Type-specific options to be considered
* @param array $options Options to be passed
* @return DataTable
*/
protected function createDataTableFromType($type, array $typeOptions = [], array $options = [])
{
return $this->factory->createFromType($type, $typeOptions, $options);
}
Then you can use it like this:
$this->createDateTable();
来源:https://stackoverflow.com/questions/56143397/how-to-subscribe-to-the-datatablefactory-service