"Unknown Entity namespace alias" exception - php

I'm experiencing troubles with my new bundle, AdminBundle, I've just created. I see the following ORMException message:
Unknown Entity namespace alias 'AdminBundle'.
This is the DefaultController.php:
<?php
namespace AdminBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
class DefaultController extends Controller
{
/**
* #Route("/dashboard", name="admin_default_dashboard")
* #return Response
*/
public function dashboardAction()
{
$manager = $this->getDoctrine()->getManager();
$rObject = $manager->getRepository('AdminBundle:Object');
return $this->render('AdminBundle:Default:dashboard.html.twig');
}
}
This is the doctrine configuration in my config.yml file:
doctrine:
dbal:
default_connection: default
connections:
default:
driver: pdo_mysql
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
orm:
auto_generate_proxy_classes: "%kernel.debug%"
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
And this is ObjectRepository.php file:
<?php
namespace AdminBundle\Repository;
use Doctrine\ORM\EntityRepository;
use AppBundle\Entity\Object;
class ObjectRepository extends EntityRepository
{
}
I've tried to check out solutions from similar threads but none of them worked to me.
edit:
This is the Object entity code: http://collabedit.com/agyh8
PS. Thanks, Arkovsky, for your advice. I'm going to change the entity name for sure.

it seems that you made a bundle without a vendor name, and that's probably why it's bugging.
When you create a bundle in Symfony use this console command in your symfony project :
php bin/console generate:bundle
Then they ask you a name for your bundle. Here you got to write something with this pattern : Bob\AdminBundle
(You can change "Bob" by whatever vendor name you like). Then follow the instructions and it should work fine.
From now, the entire name of your bundle that you are going to use in your controller is going to be : "BobAdminBundle".
Example :
return $this->render('BobAdminBundle:Default:dashboard.html.twig');

Related

Symfony table entity has itself recognized as repository as well

New to both Symfony and StackOverflow as an OP.
I'm on a way adding new mysql table entities and repositories on Symfony(4.3.2) and get stuck as I test it.
I really appreciate someone's help.
The error I got was
[2020-07-13 03:25:59] request.CRITICAL: Uncaught PHP Exception RuntimeException: "The "App\Entity\Foo" entity has a repositoryClass set to "App\Repository\Foo", but this is not a valid class. Check your class naming. If this is meant to be a service id, make sure this service exists and is tagged with "doctrine.repository_service"." at /var/www/html/bar_project/vendor/doctrine/doctrine-bundle/Repository/ContainerRepositoryFactory.php line 66 {"exception":"[object] (RuntimeException(code: 0): The \"App\\Entity\\Foo\" entity has a repositoryClass set to \"App\\Repository\\Foo\", but this is not a valid class. Check your class naming. If this is meant to be a service id, make sure this service exists and is tagged with \"doctrine.repository_service\". at /var/www/html/bar_project/vendor/doctrine/doctrine-bundle/Repository/ContainerRepositoryFactory.php:66)"} []
where Foo at /App/Entity/ is an entity for the table foo.
and the problem is that it tries to refer to Foo at App/Repository/ as its repository which doesn't exist, but not FooRepository which exists.
(Updated this paragraph following the comment from Jakumi)
(FooController.php)
$repository = $this->getDoctrine()->getRepository(Foo::class);
(Foo.php)
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table(name="foo")
* #ORM\Entity(repositoryClass="App\Repository\FooRepository") // *1
*/
class Foo
{
...
(FooRepository.php)
<?php
namespace App\Repository;
use App\Entity\Foo;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;
/**
* #method Foo|null find($id, $lockMode = null, $lockVersion = null)
* ...
*/
class FooRepository extends ServiceEntityRepository
{
...
One thing I find mysterious is that the same error log still shows up even if I remove *1.
(I think I have yarn watch and cache clear appropriately working.)
Additional Info 1
(doctrine.yaml)
doctrine:
dbal:
# configure these for your database server
driver: 'pdo_mysql'
server_version: '8.0'
charset: utf8mb4
default_table_options:
charset: utf8mb4
collate: utf8mb4_unicode_ci
# dbname:
# host:
# port:
# user:
# password:
url: '%env(resolve:DATABASE_URL)%'
options:
1002: 'SET sql_mode=(SELECT REPLACE(##sql_mode, "ONLY_FULL_GROUP_BY", ""))'
orm:
auto_generate_proxy_classes: true
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
metadata_cache_driver: apcu
result_cache_driver: apcu
query_cache_driver: apcu
connection: ~
mappings:
App:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: App
dql:
string_functions:
group_concat: DoctrineExtensions\Query\Mysql\GroupConcat
date_format: DoctrineExtensions\Query\Mysql\DateFormat

Multiple connections and entity managers in a symfony 2 / 3 application

My multi-tenant-app uses a master database, that holds information about tenants (like name, etc.) and a app-specific database per tenant.
I configured a master and some_tenant connection and entity manager in the doctrine section inside config.yml.
This gives me access to the master database from a controller (eg. for validating and getting tenant information for some_tenant based on the subdomain some_tenant.my-app.com). And it lets me use a tenant-specific database and entity manager during the application life-cycle.
The doctrine section in my config looks like this:
doctrine:
dbal:
default_connection: 'master'
connections:
master:
driver: pdo_mysql
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
some_tenant:
driver: pdo_mysql
host: "%database_host_some_tenant%"
port: "%database_port_some_tenant%"
dbname: "%database_name_some_tenant%"
user: "%database_user_some_tenant%"
password: "%database_password_some_tenant%"
charset: UTF8
orm:
auto_generate_proxy_classes: "%kernel.debug%"
entity_managers:
master:
connection: master
mappings:
BEMultiTenancyBundle: ~
some_tenant:
connection: some_tenant
mappings:
AppBundle: ~
Here comes the part, which I am unhappy with and cannot find a solution:
First of all, tenants will be more than 20. And it starts to get messy, altering the doctrine config this way.
Then there is another config file, called tenants.yml which holds more information like enabled/disabled app-features, tenant-specific themes, etc.
The file is loaded, validated using the Config Component, and a container parameter is set, so that tenants configurations are available app-wide.
I would like to store the database credentials also in that file.
I want to create connections and entity managers based on that config. One per each tenant, which can be used during the app life-cycle.
I need to have them available also at the console command bin/console doctrine:schema:update --em=some_tenant for updating each tenant's database schem and bin/console doctrine:schema:update --em=master for updating the master database scheme.
By now I guess, the only way to achieve this is to add configuration parameters to the doctrine section programmatically after the AppBundle is loaded, and before the doctrine registry is constructed with the given managers and connections.
But I cannot even find a point, where I could achive this.
Is there another way to get to point 1 and 2?
Even though there is a similiar question, which I am not sure if it is exactly about the same problem and is about 3 years old, I wanted to post this question with a bit more explanation.
The solution in comments is a straight way easy solution and it will work. The other solution I've ever meet is to dynamically replace tenant database credentails using some external conditions, i.e request HOST.
You can decorate or extend the connection factory with a service in a way, that having the request stack available (or providing the domain with ENV or console argument for other SAPI's) you can have the same entity manager (even default!) being configured on demand.
on a brief look this would look like
use Doctrine\Bundle\DoctrineBundle\ConnectionFactory;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Configuration;
use Symfony\Component\HttpFoundation\RequestStack;
class DynamicConnectionFactory extends Factory
{
/** #var RequestStack */
private $requestStack;
public function __construct(array $types, RequestStack $stack)
{
parent::__construct($types);
$this->requestStack = $stack;
}
public function createConnection(array $params, Configuration $config = null, EventManager $eventManager = null, array $mappingTypes = array())
{
$host = $this->requestStack->getMasterRequest()->getHost();
$params = $this->replaceParamsForHost(array $params, $host);
return parent::createConnection($params, $config, $eventManager, $mappingTypes);
}
private function replaceParamsForHost(array $params, $host)
{
//do your magic, i.e parse config or call Memcache service or count the stars
return array_replace($params, ['database' => $host]);
}
}
I think that, To manage multi-tenant with symfony 2/3.
We can config auto_mapping: false for ORM of doctrine.
file: config.yml
doctrine:
dbal:
default_connection: master
connections:
master:
driver: pdo_mysql
host: '%master_database_host%'
port: '%master_database_port%'
dbname: '%master_database_name%'
user: '%master_database_user%'
password: '%master_database_password%'
charset: UTF8
tenant:
driver: pdo_mysql
host: '%tenant_database_host%'
port: '%tenant_database_port%'
dbname: '%tenant_database_name%'
user: '%tenant_database_user%'
password: '%tenant_database_password%'
charset: UTF8
orm:
default_entity_manager: master
auto_generate_proxy_classes: "%kernel.debug%"
entity_managers:
master:
connection: master
auto_mapping: false
mappings:
AppBundle:
type: yml
dir: Resources/master/config/doctrine
tenant:
connection: tenant
auto_mapping: false
mappings:
AppBundle:
type: yml
dir: Resources/tenant/config/doctrine
After that, we cannot handle connection of each tenant by override connection info in request_listener like article: http://mohdhallal.github.io/blog/2014/09/12/handling-multiple-entity-managers-in-doctrine-the-smart-way/
I hope that, this practice can help someone working with multi-tenant
Regards,
Vuong Nguyen

Symfony2 Doctrine ORM Manager named "customer" does not exist

Hello I coopied the example for using two different database connections from the Symfony2 documentation: Symfony2 multiple connections documentation
So however Symfony does not find the the costumer entity manager.
(The parameters are defined properly)
doctrine:
dbal:
default_connection: default
connections:
default:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
customer:
driver: "%database_driver%"
host: "%database_host2%"
port: "%database_port2%"
dbname: "%database_name2%"
user: "%database_user2%"
password: "%database_password2%"
charset: UTF8
orm:
default_entity_manager: default
entity_managers:
default:
connection: default
mappings:
AppBundle: ~
customer:
connection: customer
mappings:
AppBundle: ~
The Controller looks like this:
class DefaultController extends Controller
{
/**
* #Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
$em = $this->get('doctrine')->getManager();
$em = $this->get('doctrine')->getManager('default');
$em = $this->get('doctrine.orm.default_entity_manager');
// Both of these return the "customer" entity manager
$customerEm = $this->get('doctrine')->getManager('customer');
$customerEm = $this->get('doctrine.orm.customer_entity_manager');
return $this->render('default/index.html.twig', array(
'base_dir' => realpath($this->container->getParameter('kernel.root_dir').'/..'),
));
}
I should get the costumer entity manager, but however Symfony throws an invalid argument exception with the message.
[2015-10-19 23:19:18] request.CRITICAL: Uncaught PHP Exception
InvalidArgumentException: "Doctrine ORM Manager named "customer" does
not exist." at /srv/www/htdocs/symfony/my_project_name/app/cache
/prod/classes.php line 7344 {"exception":"[object]
(InvalidArgumentException(code: 0): Doctrine ORM Manager named
\"customer\" does not exist. at /srv/www/htdocs/symfony/my_project_name
/app/cache/prod/classes.php:7344)"} []
I cleaned the cache with php app/console cache:clear but this does not help.
Artamiel had the right answer in a comment:
Symfony2 Doctrine ORM Manager named "customer" does not exist
cache:clear clears the dev environment by default, but looking at your error log, you receive the error in your prod environment. To clear the cache on your production environment, add -e prod flag, like this cache:clear -e prod and refresh your page.
First, I think, one declaration of entity manager in your controller is enough:
/ *** /
public function indexAction(Request $request)
{
$em = $this->get('doctrine')->getManager('default');
$customerEm = $this->get('doctrine')->getManager('customer');
/ *** /
}
Second, are you sure that you can declare the same bundle in your mapping configuration (AppBundle: ~ in this case) ?

"Class XXX is not a valid entity or a mapped super class" error when using php app/console

I'm following this Symfony2/Doctrine guide and I've come to the part where I need to create getters/setters. but I am stuck with this part:
$ php app/console doctrine:generate:entities Acme/StoreBundle/Entity/Job
I've searched the net for possible solutions (seems to mainly revolve around using 2 asterisks for the start) but couldn't find the solution.
Some info:
Bundle is properly loaded (via AppKernel.php) as I have a test "hello world" and that works.
The namespace path is correct
Job.php exists in the right folder
I'm using postgres as my database. I'm not sure if this matters.
I have tried with and without the use Doctrine\ORM\Mapping line in model class (see below for code)
I don't think I'm running a accelerator at least according to get_loaded_extensions function
Any ideas would be very helpful.
Thanks a lot :)
snippet of my settings.yml
doctrine:
dbal:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
# if using pdo_sqlite as your database driver, add the path in parameters.yml
# e.g. database_path: "%kernel.root_dir%/data/data.db3"
# path: "%database_path%"
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: true
Model class
<?php
// src/MyApp/MyBundle/Model/Job.php
namespace MyApp\MyBundle\Model;
use Doctrine\ORM\Mapping as ORM;
/**
* MyApp\MyBundle\Model\Job
*
* #ORM\Entity
* #ORM\Table(name="myschema.jobs")
*/
class Job {
/**
* #ORM\Column(name="job_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $jobid;
/**
* #ORM\Column(name="name", type="text")
*/
protected $name;
/**
* #ORM\Column(name="job_desc", type="text")
*/
protected $description;
/**
* #ORM\Column(name="personal_req", type="text")
*/
protected $requirements;
}
did you create your entity using doctrine? I saw on your Job.php entity you are using annotation as mapping format.
In error output it said doctrine can't find any mapped entities. I've been there and it solved with specific configuration of your config.yml.
Try to change this on your config.yml
doctrine:
dbal:
driver: "%database_driver%"
#etc
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: false
mappings:
MyAppMyBundle:
type: annotation #On your case it should be annotation
dir: Resources/Model/
Read this maybe it can help:
Doctrine Mapping in Symfony2 using YAML
Have you tried using following console command ?
$ php app/console doctrine:generate:entities MyApp/MyBundle/Model
I hope it will work. Your entity namespace is different than Acme/StoreBundle/Entity/Product. Your entities are in Model directory/namespace so you should use first argument of command a valid namespace. So that following cmd generates error as you have mentioned above.
$ php app/console doctrine:generate:entities Acme/StoreBundle/Entity/Product

Error generating entity with Symfony2

I am generating an Entity from php Class:
<?php
// src/Printing/Productesbundle/Entity/User.php
namespace Printing\ProductesBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="UsersStamp")
*/
class UserStamp
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue
*/
private $id;
}
?>
When I execute
php app/console doctrine:generate:entities Printing/ProductesBundle/Entity/UserStamp
it returns me the following error
[Doctrine\ORM\Mapping\MappingException]
Class "Printing\ProductesBundle\Entity\UserStamp" is not a valid entity or mapped super class.
What am i missing??
Thank you!
PS:
That's my Doctrine Configuration:
# Doctrine Configuration
doctrine:
dbal:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
# if using pdo_sqlite as your database driver, add the path in parameters.yml
# e.g. database_path: "%kernel.root_dir%/data/data.db3"
# path: "%database_path%"
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: true
Could you try command below?
app/console doctrine:generate:entities PrintingProductesBundle:UserStamp
I think you need to execute something like this
php app/console doctrine:generate:entities ProductesBundle
After trying some tricks I found the solution.
I guess the error radicates on the fact that I have entities generated previously from database.
To solve this question, you have to remove the content of the config/doctrine folder.
Thanks to #Javad to keep trying!

Categories