dozpv84422 2018-02-23 01:53
浏览 54
已采纳

如何在服务类中使用EntityManager?

I am doing app where I need register user.

RegisterController

class RegisterController extends Controller
 {
   public function indexAction(Request $request){        
   }

   public function registerUserAction(Request $request) {
    $newUser = new Register();
    $newUser = $newUser->addNewUser($username, $password);
   }
 }

Service Register

class Register
 {
   public function addNewUser($username, $password) {
    if(self::validateUsername($username) && self::validatePassword($password)) {
    $em = $this->getDoctrine()->getManager();
    }
   }
}

config/services.yaml services:

_defaults:
    autowire: true     
    autoconfigure: true 
    public: false     
App\:
    resource: '../src/*'
    exclude: '../src/{Entity,Migrations,Tests}'
App\Controller\:
    resource: '../src/Controller'
    tags: ['controller.service_arguments']

Of course I can't access doctrine and entity manager in Register and I don't know how I can do this. Please don't post symfony documentation about service containers, I read it all and don't get it.

  • 写回答

1条回答 默认 最新

  • dongzong8110 2018-02-23 03:01
    关注

    Start by injecting the entity manager into your Register service:

    namespace App\Service;
    
    use Doctrine\ORM\EntityManagerInterface;
    
    class Register
    {
        private $entityManager;
    
        public function __construct(EntityManagerInterface $entityManager)
        {
            $this->entityManager = $entityManager;
        }
        public function addNewUser($username,$password)
        {
            $user = new User($username,$password);
    
            $this->entityManager->persist($user);
    
            return $user;
        }
    }
    

    Next, we take advantage of a somewhat unusual Symfony feature sometimes known as controller action injection:

    namespace App\Controller;
    
    use App\Service\Register;
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpFoundation\Response;
    
    class RegisterController
    {
        public function registerUserAction(Request $request, Register $register)
        {
            $newUser = $register->addNewUser($username, $password);
            return new Response('Register Userx');
        }
    }
    

    And that is it. Symfony autowire takes care of connecting things up. Hopefully, this will make some of the service container documentation more understandable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装