Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 590
lepix Avatar asked Nov 18 '11 10:11

lepix


1 Answers

<?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.

like image 141
Aldo Stracquadanio Avatar answered Oct 15 '22 01:10

Aldo Stracquadanio