How to install Doctrine Extensions in a Symfony2 project - symfony

I guess that this is really trivial and stupid question, but I don't know how to install Doctrine Extensions - https://github.com/beberlei/DoctrineExtensions in my Symfony2 project. I need them because of the MONTH, YEAR functions. Where should I put their folder? And should I put the whole DoctrineExtensions folder? And where to write this:
<?php
$classLoader = new \Doctrine\Common\ClassLoader('DoctrineExtensions', "/path/to/extensions");
$classLoader->register();
In a separate file? Where to put it and how to call it?
And then is this all I need to use them:
public function findOneByYearMonthDay($year, $month, $day)
{
$emConfig = $this->getEntityManager()->getConfiguration();
$emConfig->addCustomDatetimeFunction('YEAR', 'DoctrineExtensions\Query\Mysql\Year');
$emConfig->addCustomDatetimeFunction('MONTH', 'DoctrineExtensions\Query\Mysql\Month');
$emConfig->addCustomDatetimeFunction('DAY', 'DoctrineExtensions\Query\Mysql\Day');
Thank you very much in advance and sorry once again for the question, but I couldn't find a tutorial (which makes me feel even more guilty, because I guess it's too trivial when there isn't even a tutorial)

You can install it via composer. Just add it to your composer.json and then php composer.phar update beberlei/DoctrineExtensions
"beberlei/DoctrineExtensions": "*",
Then you can register functions to your ORM
doctrine:
orm:
auto_generate_proxy_classes: %kernel.debug%
entity_managers:
default:
auto_mapping: true
dql:
datetime_functions:
MONTH: DoctrineExtensions\Query\Mysql\Month
YEAR: DoctrineExtensions\Query\Mysql\Year

There also is a nice fork by wiredmedia of #beberlei which includes even more datetime_functions like DATE() itself:
This is an unsanctioned fork of https://github.com/beberlei/DoctrineExtensions since he seems to have gone off grid and is not merging pull requests.
Unfortunately Version 0.1 just includes the fork and not all the functions.
We are waiting for a stable release:
Please create taged stable version for set in my composer #2
But you can add them manually unitl a stable version is out.

Here is how to use DoctrineExtensions in the context of Symfony using the DoctrineBundle.
First install the package DoctrineExtensions:
composer require beberlei/doctrineextensions
Then add to your doctrine configuration (doctrine.yaml file) the DQL functions you want to include in your application:
doctrine:
# Register types this way in the dbal config part
dbal:
types:
carbondatetime: DoctrineExtensions\Types\CarbonDateTimeType
# Register DQL functions in the ORM part
orm:
dql:
string_functions:
FIND_IN_SET: DoctrineExtensions\Query\Mysql\FindInSet
numeric_functions:
SIN: DoctrineExtensions\Query\Mysql\Sin
datetime_functions:
DATE: DoctrineExtensions\Query\Mysql\Date
This is an example, feel free to adjust to your needs (you can remove sections).

Related

How to generate document with Symfony 3.4 using Symfony flex

With Symfony flex, one of the change is that there is no default bundle when using the symfony/skeleton.
I don't find a way to use the command doctrine:mongodb:generate:documents in this context.
Could you please tell me how to use it ?
Exemple:
php bin\console doctrine:mongodb:generate:documents App
2018-02-17T18:35:22+00:00 [error] Error thrown while running command "doctrine:mongodb:generate:documents AppBundle --document Test". Message: "No bundle AppBundle was found."
In DoctrineODMCommand.php line 87:
No bundle AppBundle was found.
doctrine:mongodb:generate:documents [--document [DOCUMENT]] [--no-backup] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--] <command> <bundle>
This is how I setup my project
composer create-project symfony/skeleton:3.4 test
composer config "platform.ext-mongo" "1.6.16" && composer require "alcaeus/mongo-php-adapter"
composer require doctrine/mongodb-odm-bundle
Thanks
Regards,
Chris
There is a similar issue with doctrine orm and doctrine:generate:entities. The Doctrine team discourages users from using these commands and therefore does no longer want to maintain them.
I think the easiest workaround I've seen so far is:
Create a Symfony 3.3 style application using the Symfony installer.
Generate the entities in the AppBundle as you did before
Change the namespace from AppBundle to App.
Move the files into your Symfony 4 project.
Some of the Symfony team also set out to provide similar code generation in a MakerBundle. As far as I can tell there is nothing for generating ODM-style entities, but you could open an issue or contribute something for this yourself.
For reference see: https://github.com/doctrine/DoctrineBundle/issues/729
The MongoDBBundle requires you have "Bundle" but with Symfony flex you are using FrameworkBundle and not "AppBundle" unless you created it before, I think you have not created it, so it tells you that it does not exist.
You can not use the "FrameworkBundle" either beacause FrameworkBundle have other namspace and other base path, so the command to generate the documents does not know where the files are.
After a lot of time figuring out how to diry-fix it:
Create custom Bundle inside your project (EX: AppCoreBundle)
Define custom mapping inside packages/doctrine_mongodb.yaml (change type value if you use xml or yaml)
doctrine_mongodb:
auto_generate_proxy_classes: '%kernel.debug%'
auto_generate_hydrator_classes: '%kernel.debug%'
connections:
default:
server: '%env(MONGODB_URL)%'
options: {}
default_database: '%env(MONGODB_DB)%'
document_managers:
default:
auto_mapping: true
mappings:
AppCoreBundle:
is_bundle: true
type: annotation
dir: '/Document'
prefix: App\CoreBundle\Document
alias: AppCoreBundle
Change the directory "src" to "App" to avoid issues then update psr-4 namaspace inside composer.json: "App\\": "App/"
Move all Documents to the Bundle Document directory and change package names.
You will also have to change ALL references to "src" directory in your project, for example in services.yaml.
Then execute: rm -rf var/cache/* && composer install to force to clear cache and refs.
Then execute: php bin/console doctrine:mongodb:generate:documents AppCoreBundle
Important!
This solution solves compatibility problems with MongoODMBundle with Symfony 4 but it is not a correct way. The right fix involves modifying the behavior of the bundle or Symfony 4.

Provide Doctrine with custom cache factory for second level cache

Background: we're using Symfony 3.1 + Doctrine 2.5.5 + symfony doctrine bundle.
While trying to enable second level caching for our entities, we have encountered the following issue. If we use NONSTRICT_READ_WRITE, everything works fine. However, when we tried to use READ_WRITE, we got the following error
0)
Type error: Argument 2 passed to Doctrine\ORM\Cache\Persister\Entity\ReadWriteCachedEntityPersister::__construct() must be an instance of Doctrine\ORM\Cache\ConcurrentRegion, instance of Doctrine\ORM\Cache\Region\DefaultRegion given, called in vendor/doctrine/orm/lib/Doctrine/ORM/Cache/DefaultCacheFactory.php on line 133
As far as I understood, we need to actually implement our own version of ConcurrentRegion and CacheFactory to make it work (FileLockRegion does not suit us due to its usage of file system to handle cache locks). So I wrote those implementations, but the main issue now lies in following: I cannot find where to put my custom factory class' name in the configuration. We have tried the following locations in config:
1)
doctrine:
orm:
auto_generate_proxy_classes: "%kernel.debug%"
default_entity_manager: master
second_level_cache:
default_cache_factory:
class: AppBundle\Cache\MyCacheFactory
This fails due to
Unrecognized option "second_level_cache" under "doctrine.orm"
even though in our other project using Symfony 2.8 option "second_level_cache" does not throw any errors.
So we went to doctrine bundle code and found the following node description (vendor/doctrine/doctrine-bundle/DependencyInjection/Configuration.php:492)
->arrayNode('second_level_cache')
->children()
->append($this->getOrmCacheDriverNode('region_cache_driver'))
->scalarNode('region_lock_lifetime')->defaultValue(60)->end()
->booleanNode('log_enabled')->defaultValue($this->debug)->end()
->scalarNode('region_lifetime')->defaultValue(0)->end()
->booleanNode('enabled')->defaultValue(true)->end()
->scalarNode('factory')->end()
->end()
So we decided we should try this config in our master entity manager section:
2)
second_level_cache:
region_cache_driver:
type: memcache
enabled: true
log_enabled: true
factory: AppBundle\Cache\MyCacheFactory
regions:
hour_region:
lifetime: 3600
However, even though this config is considered valid, when we actually try to access the entity with configured caching, we get the error 0), which makes us think that this option is being ignored by doctrine/symfony.
Is there any way to do it via .yml config at all? Doctrine docs only propose to implement CacheFactory and provide a PHP code example, but it's still quite unclear where should this PHP code go, even if we decide to abandon the idea of putting our class in .yml config and go the PHP way.
Use type - filelock for configurate FilelockRegion
regions:
default:
cache_driver:
type: service
id: 'Doctrine\Common\Cache\RedisCache'
lifetime: 3600
type: filelock

Getting troubles when trying to install FOSUserBundle to Symfony2

When I'm trying to install FOSUserBundle I'm getting the following error:
Fatal error: Call to undefined method Symfony\Bundle\DoctrineBundle\Registry::getManager() in W:\symproject\app\cache\dev\appDevDebugProjectContainer.php on line 1039
What can it be?
I've also tried to install FOSUserBundle to a pure Symfony Standart Edition and encountered the same issue.
I followed along this documentation.
You probably have installed latest FOSUserBundle which is used for Symfony2.1.x
If you are using Symfony2.0.x change your deps file:
[FOSUserBundle]
git=git://github.com/FriendsOfSymfony/FOSUserBundle.git
target=bundles/FOS/UserBundle
version=1.2.0
then reinstall the vendors with:
php bin/vendors install
I have been using FOS User Bundle for a long time, and this weekend my automatic build stopped working with exactly the error you wrote here. So for me I then found the solution :)
It seems like the latest version of FOS User Bundle has a bug, so I added this to the deps.lock file:
FOSUserBundle f487dc16cec6003c46542a90d5193761fd91360a
In deps file I have:
[FOSUserBundle]
git=http://github.com/FriendsOfSymfony/FOSUserBundle.git
target=bundles/FOS/UserBundle
And voila! It now works!
(The commit f487d... was just chosen from the commits 4 days ago - when I know it was working)
This should fix your problem!
I've updated from 2.0.16 to 2.1 dev-master with composer, got the same error...
my solution:
In orm.xml
factory-service="doctrine" factory-method="getManager"
replace with
factory-service="doctrine" factory-method="getEntityManager"
Also if you are using Symfony 2.0.x there's not such method as getManager, instead you have to use getEntityManager to get it working.
i think you have missed Doctrine ORM mapping in config.yml
doctrine:
orm:
auto_generate_proxy_classes: %kernel.debug%
entity_managers:
default:
mappings:
FOSUserBundle: ~
try this hope this will work...

Symfony2 + doctrine2: Switch to metadata driver "yml"

a short question: How to switch to the another metadata driver than annotation. How to set the metadata driver "yml" in the config.yml?
I`ve searched google and the symfony2 docu, but didnt find anything :(
thanks
You should be able to do that with the doctrine:mapping:convert command
php app/console doctrine:mapping:convert --force yml ./src/
Double check all the options available before you run the command, though
php app/console help doctrine:mapping:convert
I realize this is an older question but you can explicitly require that doctrine use the yml driver for meta data like this:
doctrine:
orm:
entity_managers:
mappings:
MyBundleName:
type: yml
dir: path/to/ymlmetadata
Be aware that if you use this configuration style then you have to put the "defaults" config node under entity_managers instead of its usual location.

Can't enable SoftDeleteable in Symfony2 - Unrecognized options "filters"

I'm having problems trying to activate the SoftDeleteable filter in StofDoctrineExtensionsBundle. I configured it as described in the manual:
# app/config/config.yml
doctrine:
orm:
entity_managers:
default:
filters:
softdeleteable:
class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
enabled: true
But this is what I get:
[Symfony\Component\Config\Definition\Exception\InvalidConfigurationException]
Unrecognized options "filters" under "doctrine.orm.entity_managers.default"
Running bin/vendors update didn't help. What could be wrong?
First, using bin/vendors update is a bad idea because it sets all the vendors to their latest versions. You should use bin/vendors install only.
Second, make sure you are using the 1.0.x branch of StofDoctrineExtensionsBundle, because the master branch is not compatible with Symfony 2.0.x.
You can just do it yourself, it is not hard, saving you from installing another bundle:
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/filters.html

Resources