传递给:: __ construct()的参数1必须是DateTimeInterface的实例

时间:2016-06-24 10:14:36

标签: php symfony service calendar sonata-admin

我正在为奏鸣曲管理员制作日历。我正在做它作为块服务。 所以我写了一个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

刷新页面时,出现以下错误消息:

  

在渲染模板期间抛出异常(“Catchable Fatal Error:传递给CD \ CarsBundle \ Service \ Calendrier \ Jour :: __ construct()的参数1必须是DateTimeInterface的实例,没有给定,调用E:\ www \ flotte \ app \ cache \ dev \ appDevDebugProjectContainer.php在第815行并在SonataAdminBundle中定义了“):核心:第42行的dashboard.html.twig。

所以,我知道缺少参数1,它应该是DateTime接口的一个实例。但是,我找不到我怎么写它。

请有人帮助我。

1 个答案:

答案 0 :(得分:0)

您的体系结构中存在错误 - 服务应该是仅初始化(构造)一次然后在其他所有用例中重用的对象。因此,您无法使用datetime参数初始化Jour类,因为那样您的类将无法重复使用。 Jour似乎不是一种服务。

你可以

  • 每次使用时将DateTime设置为Jour类
  • 或在需要时向Jour方法提供DateTime
  • 或(我推荐这个解决方案)不要让你的Jour类成为服务并在CalendrierBlockService :: _ construct(或其他你认为最优的地方)自己初始化它。