我正试图将UrlGeneratorInterface
自动连接到DTO中,以便在我的DTO 中使用generate方法
我的DTO:中有这个
namespace AppDTO;
use JMSSerializerAnnotation as Serializer;
use JMSSerializerAnnotationExclusionPolicy;
use JMSSerializerAnnotationExpose;
use AppEntityNews;
use AppApplicationSonataMediaBundleEntityMedia;
use SymfonyComponentRoutingGeneratorUrlGeneratorInterface;
/**
* @ExclusionPolicy("all")
*
*/
class NewsDTO
{
/**
* @var integer|null
* @SerializerGroups({"news"})
* @Expose
*/
public $id;
/**
* @var string|null
* @SerializerGroups({"news"})
* @Expose
*/
public $title;
/**
* @var string|null
* @SerializerGroups({"news"})
* @Expose
*/
public $text;
/**
* @var string|null
* @SerializerGroups({"news"})
* @Expose
*/
public $cover_image;
/**
* @var string|null
* @SerializerGroups({"news"})
* @Expose
*/
public $description;
/**
* @var string|null
* @SerializerGroups({"news"})
* @Expose
*/
public $web_url;
/**
* @var string|null
* @SerializerGroups({"news"})
* @Expose
*/
public $link;
/**
* @var datetime|null
* @SerializerGroups({"news"})
* @Expose
*/
private $news_date;
private $router;
public function __construct(UrlGeneratorInterface $urlGenerator){
$this->router = $router;
}
和我的服务
parameters:
locale: 'fr'
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App:
resource: '../src/*'
exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Application,Kernel.php}'
# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class
AppController:
resource: '../src/Controller'
tags: ['controller.service_arguments']
dto.news :
class: AppDTONewsDTO
arguments:
$urlGenerator: ['@router.default']
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones
admin.videos:
class: AppAdminVideoAdmin
arguments: [~, AppEntityVideo, ~]
tags:
- { name: sonata.admin, manager_type: orm, label: Video }
admin.news:
class: AppAdminNewsAdmin
arguments: [~, AppEntityNews, ~]
tags:
- { name: sonata.admin, manager_type: orm, label: Actualités }
admin.prerolls:
class: AppAdminPrerollAdmin
arguments: [~, AppEntityPreroll, ~]
tags:
- { name: sonata.admin, manager_type: orm, label: Preroll }
但返回的错误是:
"message": "Too few arguments to function App\DTO\NewsDTO::__construct(), 0 passed in /data/www/api-dev.chartres.live/www/src/Representation/Actus.php on line 35 and exactly 1 expected"
您可能没有正确调用服务。
在/data/www/api-dev.chartres.live/www/src/Representation/Actus.php
中,您可能正在执行以下操作:
$newsDto = new NewsDTO();
但您需要使用服务注入器:
// Assuming this is a controller or has access to the `get()` service loopup
$newsDto = $this->get('dto.news');