dozpv84422 2018-02-22 17: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-22 19: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.

    展开全部

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

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部