Symfony 4 - How tu use service.yaml parameter from within Entity

扶醉桌前 提交于 2020-02-07 00:07:27

问题


I'm trying to use a parameter that i've set in service.yaml as such :

parameters: app.path.users_profile_picture: uploads/users/profile-picture

Directly from within a User Entity, And I can't figure out how to do this ?


回答1:


I'm not sure of what you're trying to do or why, it does look like there may be a better way of achieving what you want.

That being said, it is possible to use a parameter from your services.yaml in an entity, but you can't inject it directly in the entity's constructor. If you're using Doctrine you can inject it by subscribing to the postLoad event, which is dispatched after an entity is constructed by the entityManager.

Let's say you have a User entity with an attribute for the services.yaml param you want tu use:

<?php

namespace App\Entity;

private $serviceArgument;

class User
{
    /**
     * @return mixed
     */
    public function getServiceArgument()
    {
        return $this->serviceArgument;
    }

    /**
     * @param mixed $serviceArgument
     */
    public function setServiceArgument($serviceArgument): void
    {
        $this->serviceArgument = $serviceArgument;
    }
}

You need an EventSubscriber so you can do stuff on the postLoad event:

<?php

namespace App\EventSubscriber;

use App\Entity\User;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class UserSubscriber implements EventSubscriberInterface
{
    protected $serviceArgument;

    // Inject param from services.yaml
    public function __construct($serviceArgument)
    {
        $this->serviceArgument = $serviceArgument;
    }

    // Listen to postLoad event
    public static function getSubscribedEvents()
    {
        return array(
            Events::postLoad,
        );
    }

    // Set the services.yaml param on the entity
    public function postLoad(LifecycleEventArgs $args)
    {
        $user = $args->getObject();

        if ($user instanceof User) {
            $user->setServiceArgument($this->serviceArgument);
        }
    }
}

Then in your services.yaml you need to configure the subscriber and pass the param you want:

# config/services.yaml
services:
    _defaults:
        autowire: true     
        autoconfigure: true 
        public: false       

    App\EventSubscriber\UserSubscriber:
        tags:
            - { name: doctrine.event_listener, event: postLoad }
        arguments:
            $serviceArgument: 'Argument from my services.yaml'

Now you can use your param in your entity (User::getServiceArgument()).



来源:https://stackoverflow.com/questions/56619776/symfony-4-how-tu-use-service-yaml-parameter-from-within-entity

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