简体   繁体   中英

How to load an Entity from another Bundle on Symfony2

Let's say I have two Bundles :

  1. Compagny\\InterfaceBundle
  2. Compagny\\UserBundle

How can I load an Entity of UserBundle in the controller of InterfaceBundle ?

The Controller of my Compagny/InterfaceBundle :

<?php
// src/Compagny/InterfaceBundle/Controller/DefaultController.php

namespace Compagny\InterfaceBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Compagny\UserBundle\Entity; // I believed this line will do the trick, but it doesn't

class DefaultController extends Controller
{
    public function indexAction()
    {
        $user = new User();
    }
}

The Entity of my Compagny/UserBundle :

<?php

namespace Compagny\UserBundle\Entity

class User {
 public $name;
 public function setName($name) {
  // ...
 }
 public function getName() {
  // ...
 } 
}

(Let's says for this example that the User class doesn't use Doctrine2, because it doesn't need to connect to the database).

<?php
// src/Compagny/InterfaceBundle/Controller/DefaultController.php

namespace Compagny\InterfaceBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Compagny\UserBundle\Entity\User; // It's not a trick, it's PHP 5.3 namespacing!

class DefaultController extends Controller
{
    public function indexAction()
    {
        $user = new User();
    }
}

You can of course, you are just using a class from another namespace. The fact that it is an entity is not important at all! You can of course query the entity manager for that entity as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM