本文整理汇总了PHP中Symfony\Component\DependencyInjection\Container::get方法的典型用法代码示例。如果您正苦于以下问题:PHP Container::get方法的具体用法?PHP Container::get怎么用?PHP Container::get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Symfony\Component\DependencyInjection\Container
的用法示例。
在下文中一共展示了Container::get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1:
function it_sets_up_dependencies_if_class_does_contains_dependencies_method(Container $container)
{
$container->get(InjectableCompilerPass::INJECTABLES_SERVICE_ID)->willReturn($this->referenceToControllerWithDependenciesMethod);
$class = new Acme_Catalog2_IndexController();
$container->get('acme.product.catalog')->shouldBeCalled();
$this->setupDependencies($class);
}
示例2: execute
/**
* Execute the next task on the queue
*
* @param string $queue
* @param int $timeout
* @throws \Exception
* @throws \mcfedr\Queue\JobManagerBundle\Exception\UnrecoverableException
* @throws \mcfedr\Queue\JobManagerBundle\Exception\ExecuteException
*/
public function execute($queue = null, $timeout = null)
{
$job = $this->manager->get($queue, $timeout);
if (!$job) {
return;
}
$task = json_decode($job->getData(), true);
$this->logger->info('Got task', ['task' => $task['name'], 'options' => $task['options']]);
try {
/** @var Worker $worker */
$worker = $this->container->get($task['name']);
foreach ($this->preListeners as $listener) {
$listener->preTask($worker, $task['options']);
}
$worker->execute($task['options']);
foreach ($this->postListeners as $listener) {
$listener->postTask($worker, $task['options']);
}
$this->manager->delete($job);
} catch (ServiceNotFoundException $e) {
$this->manager->delete($job);
$throw = new UnrecoverableException("Service for job not found", 0, $e);
$throw->setJob($job);
throw $throw;
} catch (UnrecoverableException $e) {
$this->manager->delete($job);
$e->setJob($job);
throw $e;
} catch (\Exception $e) {
throw new ExecuteException($job, $e);
}
}
示例3: let
public function let(Container $container, Translator $translator, Session $session, TopicRepository $topicRepository, EntityRepository $repository, EntityManager $entityManager, Request $request, FormFactory $formFactory, FormBuilder $formBuilder, Form $form, FormView $formView, Topic $topic, CsrfTokenManagerAdapter $csrfTokenManagerAdapter, AbstractQuery $query, AbstractQuery $query2, ParameterBag $parameterBag, ArticleTopicRepository $articleTopicrepository, UserService $userService, User $user, TopicService $topicService, Article $article, QueryBuilder $queryBuilder, CacheService $cacheService, EventDispatcher $dispatcher)
{
$container->get('em')->willReturn($entityManager);
$container->get('session')->willReturn($session);
$container->get('request')->willReturn($request);
$container->get('translator')->willReturn($translator);
$container->get('form.factory')->willReturn($formFactory);
$container->get('form.csrf_provider')->willReturn($csrfTokenManagerAdapter);
$container->get('newscoop.cache')->willReturn($cacheService);
$container->get('user')->willReturn($userService);
$container->get('dispatcher')->willReturn($dispatcher);
$userService->getCurrentUser()->willReturn($user);
$container->get('newscoop_newscoop.topic_service')->willReturn($topicService);
$formBuilder->getForm(Argument::cetera())->willReturn($form);
$formFactory->create(Argument::cetera())->willReturn($form);
$form->createView()->willReturn($formView);
$form->handleRequest(Argument::cetera())->willReturn(true);
$form->isValid()->willReturn(true);
$entityManager->persist(Argument::any())->willReturn(true);
$entityManager->flush(Argument::any())->willReturn(true);
$entityManager->remove(Argument::any())->willReturn(true);
$entityManager->getRepository('Newscoop\\NewscoopBundle\\Entity\\Topic')->willReturn($repository);
$entityManager->getRepository('Newscoop\\Entity\\ArticleTopic')->willReturn($articleTopicrepository);
$this->setContainer($container);
$this->token = 'uTxRiEkont4XxRpTcSADPCowge7TgNONE7Y5HWd4pmY';
$request->get('_csrf_token')->willReturn($this->token);
$request->get('_code')->willReturn('en');
$request->get('_articleNumber')->willReturn('64');
$request->getLocale()->willReturn('en');
$request->get('_code', 'en')->willReturn('en');
$request->request = $parameterBag;
}
示例4: doFilter
private function doFilter(AssetInterface $asset)
{
$content = $asset->getContent();
$callback = function ($matches) {
$fs = new Filesystem();
$resource = $matches['resource'];
preg_match("/(\\@{1,2})([A-Z][A-Za-z0-9\\_\\-]*)/", $resource, $matches);
if ($resource[1] == "@") {
$resource = substr($resource, 1);
}
try {
$bundle = $this->container->get('kernel')->getBundle($matches[2]);
$path = $this->container->get('kernel')->locateResource($resource);
if ($fs->exists($path)) {
if (preg_match("/Resources\\/public\\/(.*)/", $path, $matches2)) {
$path = 'bundles/' . preg_replace('/bundle$/', '', strtolower($bundle->getName())) . '/' . $matches2[1];
if ($matches[1] == "@@") {
return $this->container->get('kernel')->getRootDir() . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'web' . DIRECTORY_SEPARATOR . $path;
}
try {
return $this->container->get('templating.helper.assets')->getUrl($path);
} catch (InactiveScopeException $e) {
return "../" . $path;
}
}
}
} catch (Exception $e) {
}
return $resource;
};
$pattern = "/(?P<resource>\\@{1,2}[A-Za-z\\_]+Bundle[A-Za-z0-9\\_\\.\\/\\-]*)/";
$asset->setContent(preg_replace_callback($pattern, $callback, $content));
}
示例5: warmUp
public function warmUp($cacheDir)
{
// we need the directory no matter the hydrator cache generation strategy.
$hydratorCacheDir = $this->container->getParameter('doctrine.odm.mongodb.hydrator_dir');
if (!file_exists($hydratorCacheDir)) {
if (false === @mkdir($hydratorCacheDir, 0777, true)) {
throw new \RuntimeException(sprintf('Unable to create the Doctrine Hydrator directory (%s)', dirname($hydratorCacheDir)));
}
} else {
if (!is_writable($hydratorCacheDir)) {
throw new \RuntimeException(sprintf('Doctrine Hydrator directory (%s) is not writeable for the current system user.', $hydratorCacheDir));
}
}
// if hydrators are autogenerated we don't need to generate them in the cache warmer.
if ($this->container->getParameter('doctrine.odm.mongodb.auto_generate_hydrator_classes') === true) {
return;
}
$documentManagers = $this->container->getParameter('doctrine.odm.mongodb.document_managers');
foreach ($documentManagers as $documentManagerName) {
$dm = $this->container->get(sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManagerName));
/* @var $dm Doctrine\ODM\MongoDB\DocumentManager */
$classes = $dm->getMetadataFactory()->getAllMetadata();
$dm->getHydratorFactory()->generateHydratorClasses($classes);
}
}
示例6: setSignalHandlers
/**
* Sets the signal handlers that we use during execution
*/
private function setSignalHandlers()
{
$this->container->get('logger')->debug('Setting signal handlers');
pcntl_signal(SIGTERM, [$this, 'signalHandler']);
pcntl_signal(SIGINT, [$this, 'signalHandler']);
pcntl_signal(SIGHUP, [$this, 'signalHandler']);
}
示例7: testToolbarConfig
/**
* @dataProvider getDebugModes
*/
public function testToolbarConfig($enabled)
{
$extension = new WebProfilerExtension();
$extension->load(array(array('toolbar' => $enabled)), $this->container);
$this->assertSame($enabled, $this->container->get('web_profiler.debug_toolbar')->isEnabled());
$this->assertSaneContainer($this->getDumpedContainer());
}
示例8: __construct
public function __construct(Container $container)
{
$this->container = $container;
$this->request = $container->get('request');
$this->em = $container->get('doctrine')->getManager();
$this->user = $container->get('security.context')->getToken()->getUser();
}
示例9: onKernelView
/**
* @DI\Observe("kernel.view", priority = 255)
*/
public function onKernelView(GetResponseEvent $event)
{
$responseData = $event->getControllerResult();
if ($responseData instanceof Response) {
return;
}
$response = new JsonResponse($responseData);
$securityContext = $this->container->get('security.context');
$token = $securityContext->getToken();
$userId = $token->getUsername();
if ($userId != 'anon.') {
if (in_array('ROLE_ADMIN', array_map(function ($role) {
return $role->getRole();
}, $token->getRoles()))) {
$access = self::ACCESS_ADMIN;
} else {
if (array_key_exists('ownerId', $responseData) && $responseData['ownerId'] == $userId) {
$response->headers->set('owner-id', $responseData['ownerId']);
$access = self::ACCESS_AUTHOR;
} else {
$access = self::ACCESS_READER;
}
}
} else {
$access = self::ACCESS_ANONYMOUS;
}
$roles = "";
foreach ($token->getRoles() as $role) {
$roles = $roles . ", " . $role->getRole();
}
$response->headers->set('user-id', $userId);
$response->headers->set('roles', $roles);
$response->headers->set(self::ACCESS_HEADER_NAME, $access);
$event->setResponse($response);
}
示例10: getSearchManager
public static function getSearchManager(Container $container = null, $vertical)
{
if ($vertical != '') {
return $container->get('rmc_' . $vertical . '.search_manager');
}
return $container->get('rmc_core.ad_search_manager');
}
示例11: let
public function let(ArticleService $articleService, AuthorService $authorService, CacheService $cacheService, Container $container, ArticleRepository $articleRepository, LanguageRepository $languageRepository, ArticleTypeRepository $articleTypeRepository, PublicationRepository $publicationRepository, IssueRepository $issueRepository, SectionRepository $sectionRepository, AuthorTypeRepository $authorTypeRepository, EntityManager $entityManager, Request $request, FormFactory $formFactory, FormBuilder $formBuilder, Form $form, FormView $formView, User $user, UserService $userService, Article $article, Publication $publication, ArticleType $articleType, Issue $issue, Section $section, Language $language, Author $author, AuthorType $authorType, AbstractQuery $query, SecurityContext $security, TokenStorage $tokenStorage, TokenInterface $token, Router $router)
{
$container->get('em')->willReturn($entityManager);
$container->get('request')->willReturn($request);
$container->get('user')->willReturn($userService);
$container->get('form.factory')->willReturn($formFactory);
$container->get('newscoop_newscoop.article_service')->willReturn($articleService);
$container->get('author')->willReturn($authorService);
$container->get('newscoop.cache')->willReturn($cacheService);
$container->get('router')->willReturn($router);
$formBuilder->getForm(Argument::cetera())->willReturn($form);
$formFactory->create(Argument::cetera())->willReturn($form);
$form->createView()->willReturn($formView);
$form->handleRequest(Argument::cetera())->willReturn(true);
$form->isValid()->willReturn(true);
$security->getToken()->willReturn($token);
$container->get('security.context')->willReturn($security);
$container->has('security.context')->willReturn(true);
$container->has('security.token_storage')->willReturn(true);
$container->get('security.token_storage')->willReturn($tokenStorage);
$this->setContainer($container);
$entityManager->getRepository('Newscoop\\Entity\\Article')->willReturn($articleRepository);
$entityManager->getRepository('Newscoop\\Entity\\Language')->willReturn($languageRepository);
$entityManager->getRepository('Newscoop\\Entity\\ArticleType')->willReturn($articleTypeRepository);
$entityManager->getRepository('Newscoop\\Entity\\Publication')->willReturn($publicationRepository);
$entityManager->getRepository('Newscoop\\Entity\\Issue')->willReturn($issueRepository);
$entityManager->getRepository('Newscoop\\Entity\\Section')->willReturn($sectionRepository);
$entityManager->getRepository('Newscoop\\Entity\\AuthorType')->willReturn($authorTypeRepository);
$articleRepository->getArticle(Argument::cetera())->willReturn($query);
$entityManager->flush(Argument::any())->willReturn(true);
$userService->getCurrentUser()->willReturn($user);
$number = 64;
$language = "en";
}
示例12: preRemove
/**
* Перед удаление альбома, удаляем все фотограффии, находящиеся в нем,
* и уменьшаем у всех последующих альбомов sortIndex на 10
*
* @param LifecycleEventArgs $args
*/
public function preRemove(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$em = $args->getEntityManager();
if ($entity instanceof \PhotoBundle\Entity\Album) {
$photos = $entity->getPhotos();
foreach ($photos as $photo) {
$em->remove($photo);
}
$sortIndex = $entity->getSortIndex();
$albums = $em->getRepository('PhotoBundle:Album')->getAlbumsWithMoreSortIndex($sortIndex);
foreach ($albums as $album) {
$currentSortIndex = $album->getSortIndex();
$album->setSortIndex($currentSortIndex - 10);
}
} elseif ($entity instanceof Photo) {
$name = $entity->getName();
$pathToImageDirectory = $this->_container->get('request')->server->get('DOCUMENT_ROOT') . '/uploaded/images';
$paths = array($pathToImageDirectory . '/800x800/', $pathToImageDirectory . '/200x200/');
foreach ($paths as $path) {
$fullName = $path . $name;
if (file_exists($fullName)) {
unlink($fullName);
}
}
}
}
示例13: getSite
public function getSite()
{
if ($this->site === null) {
$host = $this->container->get('request')->getHost();
$cleanHost = $this->removeUrlPattern($host);
$sites = $this->em->getRepository('SymbbCoreSiteBundle:Site')->findBy(array());
foreach ($sites as $site) {
$domains = $site->getDomainArray();
foreach ($domains as $domain) {
if ($this->removeUrlPattern($domain) == $cleanHost) {
$this->site = $site;
return $this->site;
}
}
}
if ($this->site === null) {
if (!empty($sites)) {
$this->site = reset($sites);
} else {
$this->site = new \Symbb\Core\SiteBundle\Entity\Site();
}
}
}
return $this->site;
}
示例14: createTicket
/**
* @param Event $event
* @param User $user
*
* @return Ticket
*/
public function createTicket($event, $user)
{
// @todo це ще треба передивитись і поправити
$em = $this->container->get('doctrine.orm.default_entity_manager');
// Вытягиваем скидку из конфига
$paymentsConfig = $this->container->getParameter('stfalcon_event.config');
$discount = (double) $paymentsConfig['discount'];
$ticket = new Ticket();
$ticket->setEvent($event);
$ticket->setUser($user);
$ticket->setAmountWithoutDiscount($event->getCost());
$paidPayments = $em->getRepository('StfalconEventBundle:Payment')->findPaidPaymentsForUser($user);
// если пользователь имеет оплаченные события,
// то он получает скидку (если для события разрешена такая скидка)
if (count($paidPayments) > 0 && $event->getUseDiscounts()) {
$cost = $event->getCost() - $event->getCost() * $discount;
$hasDiscount = true;
} else {
$cost = $event->getCost();
$hasDiscount = false;
}
$ticket->setAmount($cost);
$ticket->setHasDiscount($hasDiscount);
$em->persist($ticket);
$em->flush();
return $ticket;
}
示例15: dump
public function dump(AssetInterface $asset)
{
$writer = new \Assetic\AssetWriter(sys_get_temp_dir(), $this->container->getParameter('assetic.variables'));
$ref = new \ReflectionMethod($writer, 'getCombinations');
$ref->setAccessible(true);
$name = $asset->getSourcePath();
$type = substr($name, strrpos($name, '.') + 1);
switch ($type) {
case 'coffee':
$asset->ensureFilter($this->container->get('assetic.filter.coffee'));
$type = 'js';
break;
case 'less':
$asset->ensureFilter($this->container->get('assetic.filter.less'));
$type = 'css';
break;
}
$combinations = $ref->invoke($writer, $asset->getVars());
$asset->setValues($combinations[0]);
$asset->load();
$content = $asset->getContent();
// because the assetic cssrewrite makes bullshit here, we need to reimplement the filter
if ($type === 'css') {
$content = $this->cssFilter($content, '/' . dirname($asset->getSourcePath()));
}
return $content;
}