How to subscribe to the DataTableFactory service?

坚强是说给别人听的谎言 提交于 2021-02-08 06:41:40

问题


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 AbstractController instead, which is currently recommended practice, ensure you subscribe to the DataTableFactory service 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!