【问题标题】:Argument 1 passed to ::__construct() must be an instance of DateTimeInterface传递给 ::__construct() 的参数 1 必须是 DateTimeInterface 的实例
【发布时间】:2016-06-24 10:14:36
【问题描述】:

我正在将日历构建到奏鸣曲管理员中。我把它作为一个块服务来做。 于是我写了一个CalendarBlockService.php

<?php

namespace CD\CarsBundle\Block\Service;

use Sonata\BlockBundle\Block\BlockContextInterface;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Validator\ErrorElement;
use Sonata\AdminBundle\Admin\Pool;
use Sonata\BlockBundle\Model\BlockInterface;
use Sonata\BlockBundle\Block\BaseBlockService;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Security\Core\SecurityContext;
use Doctrine\ORM\EntityManager; // mis car je vais devoir récupérer les immatriculations disponibles par jour => donc requête bdd dans repository => utilisation de l'entitymanager




class CalendrierBlockService extends BaseBlockService
{
	// mettre le code des méthodes nécessaires pour le calendrier (block service) avec les données à retrouver dedans

	/**
	 * @var Symfony\Component\Security\Core\SecurityContext
	 */
	protected $securityContext; 

	/**
	 * @var EntityManager
	 */
	protected $em;

	/**
	 * @var \CD\CarsBundle\Service\Calendrier\Calendrier
	 */
	private $calendrier;

	/**
	 * @var \CD\CarsBundle\Service\Calendrier\Jour
	 */
	private $jour;




		// CalendrierBlockService Constructor

	/**
	 * @param string $name
	 * @param EngineInterface $templating
	 * @param Pool $pool
	 * @param EntityManager $em
	 * @param SecurityContext $securityContext
	 * @param Calendrier $calendrier
	 * @param Jour $jour
	 */
	public function __construct(
		$name,
		EngineInterface $templating,
		Pool $pool,
		EntityManager $em,
		SecurityContext $securityContext,
		Calendrier $calendrier,
		Jour $jour)
	{
		parent::__construct($name, $templating);

		$this->pool            = $pool;
		$this->em              = $em;
		$this->securityContext = $securityContext;
		$this->calendrier      = $calendrier;
		$this->jour            = $jour;
	}
	
		// Name

	/**
     * {@inheritdoc}
     */
	public function getName()
	{
		return 'Disponibilités';
	}

		// Default settings (valid options for a block of this type)

	/**
     * {@inheritdoc}
     */
	public function setDefaultSettings(OptionsResolverInterface $resolver)
	{
		$resolver->setDefaults(array(
			'title'    => 'Calendrier des disponibilités',
			'template' => 'CDCarsBundle:Block:calendrier.html.twig',
		));
	}

	/**
	 * @return array
	 */
	public function getDefaultSettings()
	{
		return array();
	}

        // Implement the execute method which must return a response object, which is used to render the block
		// The block context knows the defaults settings, but they can be overwritten in the call to render the block

	/**
	 * {@inheritdoc}
	 */
	public function execute(BlockContextInterface $blockContext, Response $response = null)
	{
		// Pick up the instance of the vehicles repository
		$repovehicules = $this->em->getRepository('CDCarsBundle:Vehicules');

		// Get the available plates numbers (an array) which will be render to a template
		$immatriculations = $repovehicules->getAvailables();

		// Pick up the calendar ( !!! be careful about the config and the construct if the calendar is declared as a service)
		$calendar = new CD\CarsBundle\Resources\views\Block();   //>>>>> right or not?

		// Setup the variables entered into the method "render Response" (the 3 first are required)
		$variable = array(
			'block'            => $blockContext->getBlock(),
			'base_template'    => $this->pool->getTemplate('CDCarsBundle:Block:calendrier.html.twig'),
			'seetings'         => $blockContext->getSettings(),
			'immatriculations' => $immatriculations,
			'calendrier'       => $calendar
			);

		// Now execute the template and send a response
		return $this->renderResponse($blockContext->getTemplate(), $variable, $response);
	}

		// To edit in sonata admin

	/**
     * {@inheritdoc}
     */
	public function buildEditForm(FormMapper $formMapper, BlockInterface $block)
	{
	}

		// To validate in sonata admin

	/**
     * {@inheritdoc}
     */
	public function validateBlock(ErrorElement $errorElement, BlockInterface $block)
	{
	}

		
}

还有Calendrier.php(没写完)

<?php

namespace  CD\CarsBundle\Service\Calendrier;

class Calendrier
{
	// With this file, I collect all the informations of each days of each month of the year

	// Pick up the days of a month (array with days which are numbered)

	/**
	 * @param string | interger $month
	 * @return CD\CarsBundle\Service\Calendrier\Jour
	 */
	public function getDays($month)
	{
		return $this->days[$month];
	}

}

还有 Jour.php

<?php

namespace CD\CarsBundle\Service\Calendrier;

class Jour
{
	// With this file, I collect all the informations about one day (example: 21-09-2016)

	// Days are defined with constants values (reusable everywhere in the app)

	const WEEK_MONDAY    = "1";
	const WEEK_TUESDAY   = "2";
	const WEEK_WEDNESDAY = "3";
	const WEEK_THURSDAY  = "4";
	const WEEK_FRIDAY    = "5";
	const WEEK_SATURDAY  = "6";
	const WEEK_SUNDAY    = "7";

	/**
	 * Then the date is build (format year-month-day) with a constructor
	 * @param \DateTimeInterface $day
	 */
	public function __construct(\DateTimeInterface $day)
	{
		$this->year    = $day->format('Y');
		$this->month   = $day->format('m');
		$this->day     = $day->format('Y-m-d');
		$this->dayWeek = $day->getDayWeek($day);
	}

	/**
	 * Transform date from DateTime format to String format
	 *
	 * @return string
	 */
	public function __toString()
	{
		return $this->getDateString();
	}

	/**
	 * Pick up the date in string
	 * @return string
	 */
	public function getDateString()
	{
		return $this->year .''. $this->month .''. $this->day;
	}

	/**
	 * Pick up the year
	 * @return string
	 */
	public function getYear()
	{
		return $this->year;
	}

	/**
	 * Pick up the month
	 * @return string
	 */
	public function getMonth()
	{
		return $this->month;
	}

	/**
	 * Pick up the day
	 * @return string
	 */
	public function getDay()
	{
		return $this->day;
	}

	/**
	 * Pick up the day week (number of the day -> example: monday = 1)
	 * @return string
	 */
	public function getDayWeek()
	{
		return $this->dayWeek;
	}

	/**
	 * Saturdays and Sundays are days off (days without bookings, so no need to have the list of available vehicles for those 2 days) -> DayWithout
	 * @return boolean
	 */
	public function getDayWithout()
	{
		return $this->dayWithout;
	}

	// Only the current class will have access to the field or method.

	private $day;
	private $month;
	private $year;
	private $dayWeek;
	private $dayWithout;
}

我在我的 bundle/Resources/config/services.yml 中声明为服务

sonata.block.service.calendrier:
        class: CD\CarsBundle\Block\Service\CalendrierBlockService
        arguments:
            - "sonata.block.service.calendrier"
            - '@templating'
            - '@doctrine.orm.entity_manager'
            - '@security.context'
            - '@cd_cars.calendrier'
            - '@cd_cars.jour'
        tags:
            - { name: sonata.block }

    cd_cars.calendrier:
        class: CD\CarsBundle\Service\Calendrier\Calendrier

    cd_cars.jour:
        class: CD\CarsBundle\Service\Calendrier\Jour

当我刷新页面时,我收到以下错误消息:

在渲染模板期间引发了异常(“可捕获的致命错误:传递给 CD\CarsBundle\Service\Calendrier\Jour::__construct() 的参数 1 必须是 DateTimeInterface 的实例,没有给出,调用E:\www\flotte\app\cache\dev\appDevDebugProjectContainer.php 在第 815 行并在 SonataAdminBundle:Core:dashboard.html.twig 第 42 行定义")。

所以,我知道参数 1 丢失了,它应该是 DateTime 接口的一个实例。但是,我找不到如何编写它。

请大家帮帮我。

【问题讨论】:

  • 嗨 Coralie,一开始我也用法语编码(cmets 和类名)。我可以鼓励你用英语编码,以防你的程序应该由其他人调试。想象一下,你必须调试一些用波兰语注释的东西......非常困难(这是我的情况......)...... [只是一个评论]
  • 我理解完全不用担心。对于我的个人项目,我用英语编码。但是,这个实习项目必须用法语编码(客户要求)。所以我必须尊重这一点。

标签: php symfony service calendar sonata-admin


【解决方案1】:

您的架构中有一个错误 - 服务应该是只初始化(构造)一次然后在所有其他用例中重用的对象。所以你不能用 datetime 参数初始化你的 Jour 类,因为那样你的类就不能重用了。 Jour 似乎不是一项服务。

你可以

  • 每次使用时将 DateTime 设置为 Jour 类
  • 或在需要时将 DateTime 提供给 Jour 方法
  • 或者(我推荐这个解决方案)不要让您的 Jour 类成为服务并在 CalendrierBlockService::_construct(或您认为最佳的任何其他地方)中自行初始化它

【讨论】:

    猜你喜欢
    • 2018-12-15
    • 1970-01-01
    • 2015-05-11
    • 2017-04-06
    • 2018-08-14
    • 2018-01-09
    • 2017-06-12
    • 2021-05-16
    • 2020-06-15
    相关资源
    最近更新 更多