Silex and Doctrine - ORMException: Unknown Entity namespace alias [semi fixed] - doctrine-orm

I'm trying to use the Doctrine components in my app built using silex. I was able to get it to work - well almost.
I have my "User" entity and the corresponding repository
When doing
$app['em']->getRepository('Foo\Entity\User')->findAll()
works as expected, however when trying to make a custom query
$this->getEntityManager()
->createQuery(
'SELECT
u
FROM
Foo:User u
WHERE c.id = :x'
)
->setParameter('x',$in)
->getResult();
I get this exception
ORMException: Unknown Entity namespace alias 'Foo'
Please ignore the fact that I can make a select with findById() or findBy(array('id'=>$in)) the problem is with the custom query
This are my configs
$app['orm.em.options'] = array(
'mappings' => array(
array(
'type' => 'annotation',
'namespace' => 'Foo\Entity',
'alias' => 'core',
'path' => '%app.path%/src/Foo/Entity',
'use_simple_annotation_reader' => false,
)
));
and
$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/src/Foo/Entity"));
$params = $app['db.options'];
$app['em'] = EntityManager::create($params, $config);
After some research possible solutions:
auto_mapping: true => tried, no success
registering the namespace => tried, not sure if right was done so may be the solution, please advice how to do it right
besides all this I have tried to search for git repos with similar 'usage' but didn't get it :(
UPDATE
for the moment I use the following line in my query and it works
FROM
InstaLikes\Entity\User u

When you create custom queries, you should use the fully namespace, in this case:
Foo\Entity\User

I am assuming you have checked the alias you have given in the mappings options?
$app['orm.em.options'] = array(
'mappings' => array(
array(
'type' => 'annotation',
'namespace' => 'Foo\Entity',
'alias' => 'core',
'path' => '%app.path%/src/Foo/Entity',
'use_simple_annotation_reader' => false,
)
));
Should that alias option not be set to Foo instead?

Related

Working but hidden/missing entities

I have several modules in my zf2 application, they all have their own entities and all on the same connection.
A little diagram to explain the situation :
-Module 1
-Entity A
-Entity B
-Module 2
-Entity C
-Entity B
(all on the same database connection)
The problem is all the entities are working, i can fetch, update them, etc. but some are "invisible". I have some cross-module relations and they are working fine too.
For exemple, all entities from module 2 does not appear when I use the php public/index.php orm:info command nor in the Zend Developer Toolbar.
When I edit an entity, I have to manually update the database as php public/index.php orm:schema-tool:update says Nothing to update - your database is already in sync with the current entity metadata.
The entities can be fetched, they are just not "seen" by the ZDT nor the terminal, I don't know what I did wrong.
Thanks for your help
This is often caused when the path to the entities has not been declared in your config:
<?php
return array(
'doctrine' => array(
'driver' => array(
// defines an annotation driver with two paths, and names it `my_annotation_driver`
'my_annotation_driver' => array(
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'cache' => 'array',
'paths' => array(
'path/to/my/entities',
'another/path'
),
),
// default metadata driver, aggregates all other drivers into a single one.
// Override `orm_default` only if you know what you're doing
'orm_default' => array(
'drivers' => array(
// register `my_annotation_driver` for any entity under namespace `My\Namespace`
'My\Namespace' => 'my_annotation_driver'
)
)
)
)
);

How to add regex to attribute name in custom validations in Laravel?

In custom validation as shown below:
'custom' => array(
'attribute-name' => array(
'rule-name' => 'custom-message',
),
),
How is it possible to define regex along with the attribute-name-{regex} as well?!
Example:
'custom' => array(
'institute_regex:{/d{1}}' => array(
'required' => 'the field is required',
),
),
I think that might be what you were looking for ages ago, but anyway, here is what I did.
Had to find a way to define custom validation messages (in another language) for inputs dynamically generated in the frontend. The result is that I would get the following type of classes:
project_name-1, -2, -3 etc to keep it simple.
So what I did, and it worked just fine for me was adding the following lines to my validation.php file (whatever the language is):
'project_name-*' => [
'required' => 'Please name your project.',
],
And voilĂ , I hope it will help someone!

zf2 doctrine2 and Zend\Db\Adapter\Adapter using one db connection

I use doctrine2 with ZF2, some of my libraries work with Zend\Db\Adapter\Adapter, others with doctrine2. Now, they connect to database twice. Is it possible to use one db connection in doctrine and standard ZF2 db adapter?
The DoctrineORM module accepts a PDO resource or a service name where the instance can be located in the service manager instead of the usual connection params.
First step is to create a service factory which retrieves the PDO resource from the Zend\Db\Adapter\Adapter service
<?php
namespace Application\Db\Service;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\Exception\ServiceNotCreatedException;
class PdoResourceFactory implements FactoryInterface
{
/**
* #param ServiceLocatorInterface $serviceLocator
* #return \PDO resource
*/
public function createService(ServiceLocatorInterface $services)
{
$dbAdapter = $services->get('Zend\Db\Adapter\Adapter');
$pdo = $dbAdapter->getDriver()->getConnection()->getResource();
if (!$pdo instanceof \PDO) {
throw new ServiceNotCreatedException('Connection resource must be an instance of PDO');
}
return $pdo;
}
}
Once you have the factory, it's just a case of adding it to the service manager, configuring the db params for Zend\Db\Adapter\Adapter and telling doctrine to use the existing PdoResource from the service manager to connect.
Assuming you did this all in one file, let's say dbconn.local.php...
<?php
return array (
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
// include the pdo resource factory
'PdoResource' => 'Application\Db\Service\PdoResourceFactory',
),
),
// db adapter config
'db' => array(
'driver' => 'pdo',
'dsn' => 'mysql:dbname=database;host=127.0.0.1',
'username' => 'username',
'password' => 'password',
),
'doctrine' => array (
'connection' => array (
'orm_default' => array (
'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
// use the resource from the zend adapter
'pdo' => 'PdoResource',
),
),
),
);
Sorry for posting this as new answer but I am not able to add a comment to Crisp's answer since my reputation is too low because I only registered to stackoverflow for writing this comment:
In the dbconn.local.php that Crisp posted be sure to set dbname to null like in the following snippet:
Addition to Crisp's answer:
<?php
return array(
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
// the lazy way of Crisp's PdoResourceFactory:
'PdoResource' => function (ServiceLocatorInterface $services) {
$dbAdapter = $services->get('Zend\Db\Adapter\Adapter');
$pdo = $dbAdapter->getDriver()->getConnection()->getResource();
if (!$pdo instanceof \PDO) {
throw new ServiceNotCreatedException('Connection resource must be an instance of PDO');
}
return $pdo;
},
),
),
// db adapter config
'db' => array(
'driver' => 'pdo',
'dsn' => 'mysql:dbname=database;host=127.0.0.1',
'username' => 'username',
'password' => 'password',
),
'doctrine' => array (
'connection' => array (
'orm_default' => array (
'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
// use the resource from the zend adapter
'pdo' => 'PdoResource',
// important addition to Crisp's answer:
'params' => array(
'dbname' => null,
),
),
),
),
);
And now here is why this is important:
When calling
$em->getConnection()->getDatabase();
on your EntityManager without having set the dbname to null you will get "database" as the name of your database because this is the default value which is set by the module.config.php of the DoctrineORMModule as you can see here. Setting the dbname to null will cause your Doctrine\DBAL\Driver\PDOMySql\Driver which extends Doctrine\DBAL\Driver\AbstractMySQLDriver to load the name of the database via SELECT DATABASE() from the database itself as you can see here.
Also not setting the dbname to null (or to the correct database name) will cause the schemaInSyncWithMetadata() function of the Doctrine\ORM\Tools\SchemaValidator to always return false since it cannot load the current database setup because it uses the Doctrine\ORM\Tools\SchemaTool which uses the EntityManager's Connection which thinks that the database being used is called "database".
So I hope someone can use this information to save some time. I wasted half the day to figure that out.
And many thanks to Crisp again for his answer that saved me a lot of time.

How to use DoctineModule ObjectSelect based on custom repository method?

I have a table with a list of person that belong to different categories A and B for example. My problem is that i have a form with DoctrineModule ObjectSelect and i want to show in the ObjectSelect only the name of persons of Category A.
I find this https://github.com/doctrine/DoctrineModule/blob/master/docs/form-element.md#example-3--extended-version but the example is not clear for me and i don't know how to adapt it to my case.
Thank you.
excuse me for my english.
It's actually quite similar to the example you were looking at (I guess that's why there is no example for it), the only difference is that instead of using find/findBy/... you pass your custom repository name as name key, with code similar to this:
$this->add(array(
'name' => 'my-select-object',
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'attributes' => array(
),
'options' => array(
'label' => 'My Label',
'object_manager' => $entityManager,
'target_class' => 'Application\Entity\MyEntity',
'property' => 'name',
'is_method' => true,
'find_method' => array(
'name' => 'myCustomRepositoryMethod',
'params' => array(
),
),
),
));
Also notice that your entity needs to know about repository existence, so make sure it uses this line:
#ORM\Entity(repositoryClass="Application\Entity\Repository\MyCustomRepository")
So when you open the form with this ObjectSelect it will call you repository method instead of loading the dropdown directly. That method should just return an array of entity objects which are then used by ObjectSelect to generate select element's options.

How to add a custom DQL function in Doctrine 2 using Zend Framework 2

Well the question pretty much lies in the title. I've read the docs and what I can't find out is how to register the function to my ORM Configuration.
Any help here? Thanks!
Edit: Okay I've done it as Sam said, and made my own class and registered it like
'numeric_functions' => array(
'LOG10' => 'Admin\Model\Log10',
),
However it can't find the class and gives the error
Class 'Admin\Model\Log10' not found in C:\webserver\apache\htdocs\test\vendor\doctrine\orm\lib\Doctrine\ORM\Query\Parser.php on line 3322
Any idea on why this happens?
Actually the link that #foozy gave you is all that you'd need. You simply extend your doctrine configuration array:
return array(
'doctrine' => array(
'connection' => array(
'orm_default' => array(
// Foo
)
),
'configuration' => array(
'orm_default' => array(
'numeric_functions' => array(
'MD5' => 'DoctrineExtensions\Query\Mysql\Md5'
),
'datetime_functions' => array(),
'string_functions' => array(),
'metadata_cache' => 'filesystem',
'query_cache' => 'filesystem',
'result_cache' => 'filesystem',
)
)
)
);
The error is connected to DoctrineExtensions autoload. For me both solutions from How to implement beberlei doctrine extensions in zend framework 2 (manual injection of custom functions and applying via config) worked.