Installing Doctrine extensions in a Symfony 2 project causes Fatal Error - php

Here is the problem : I don't succeed to install doctrine extensions with symphony 2, especially timestampable. I follow this tutorial
How I proceed :
I add this lines in deps file :
[gedmo-doctrine-extensions]
git=http://github.com/l3pp4rd/DoctrineExtensions.git
[Stof-DoctrineExtensionsBundle]
git=https://github.com/stof/StofDoctrineExtensionsBundle.git
target=/bundles/Stof/DoctrineExtensionsBundle
Then I enter the line
./bin/vendors install --reinstall
All is fine.
Then I activate extensions in concerned files
# config.yml
stof_doctrine_extensions:
default_locale: fr_FR
orm:
default:
timestampable: true
# AppKernel.php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
[...]
new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
[...]
);
# autoload.php
use Symfony\Component\ClassLoader\UniversalClassLoader;
use Doctrine\Common\Annotations\AnnotationRegistry;
$loader = new UniversalClassLoader();
$loader->registerNamespaces(array(
'Gedmo' => __DIR__.'/../vendor/gedmo-doctrine-extensions/lib',
'Stof' => __DIR__.'/../vendor/bundles',
[...]
));
At last, I add annotate my entity
/**
* #var datetime $updatedAt
*
* #ORM\Column(name="updated_at", type="datetime")
* #Gedmo:Timestampable(on="update")
*/
private $updatedAt;
But I have this error :
Fatal error: Class 'Gedmo\Timestampable\TimestampableListener' not found in /Symfony/app/cache/dev/appDevDebugProjectContainer.php on line 203
What do I do wrong ?

Using #Gedmo\Timestampable(on="update") and putting the right path when registering the namespace seems to solve the problem.

For Symfony 2.0.x and Doctrine 2.1.x. projects you'll need to specify the compatible versions of the extensions in deps, this is what worked for me:
[DoctrineExtensions]
git=https://github.com/l3pp4rd/DoctrineExtensions.git
target=/gedmo-doctrine-extensions
version=origin/doctrine2.1.x
[StofDoctrineExtensionsBundle]
git=https://github.com/stof/StofDoctrineExtensionsBundle.git
target=/bundles/Stof/DoctrineExtensionsBundle
version=1.0.2

Related

UserPasswordEncoderInterface Autowiring Not Working Symfony 4.4

I have a super basic API endpoint with a fresh install of symfony 4.4 and I'm getting the following error:
Cannot autowire argument $passwordEncoder of
"App\Controller\AuthenticationController::authenticateAction()": it
references interface
"Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface"
but no such service exists.
My Controller:
<?php
namespace App\Controller;
use App\Entity\User;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\Annotations\Route;
use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
/**
* Class AuthenticationController
*
* #package App\Controller
* #Route("/api/authentication")
*/
class AuthenticationController extends AbstractFOSRestController {
/**
* #Rest\Get("/authenticate")
*
* #param Request $request
* #param UserPasswordEncoderInterface $passwordEncoder
* #param JWTEncoderInterface $JWTEncoder
*
* #return Response
*/
public function authenticateAction (Request $request, UserPasswordEncoderInterface $passwordEncoder, JWTEncoderInterface $JWTEncoder) {
exit;
}
}
If I remove UserPasswordEncoderInterface $passwordEncoder I get a successful nothing (expected for now). My User Entity is nothing special, and extends UserInterface correctly.
services.yaml
# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.
# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
resource: '../src/'
exclude:
- '../src/DependencyInjection/'
- '../src/Entity/'
- '../src/Kernel.php'
- '../src/Tests/'
# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class
App\Controller\:
resource: '../src/Controller/'
tags: ['controller.service_arguments']
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones
Using Symfony 4.4 and php 7.2.20
Almost certain this is some sort of configuration issue, but I'm not following what I did wrong.
Man am I smart, it was a config issue!
My security.yaml file was in main /config directory and not in the /config/packages directory. Ok maybe I'm not that smart...
Not sure how it got there. I think some out-dated package couldn't find it in the config/packages directory.
There goes 48 hours of my life...

doctrine odm annotations or composer autoload.php not working?

I'm trying to use Doctrine MongoDB ODM 2.0 beta on a project with the Yii2 framework, with composer version 1.8.4 and PHP 7.2, but I keep getting the error Fatal error: Uncaught Error: Call to a member function add() on boolean where the code runs $loader->add('Documents', __DIR__);
bootstrap.php file (in DIR/bootstrap.php):
<?php
use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\ODM\MongoDB\Configuration;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver;
if ( ! file_exists($file = 'C:/path/to/vendor/autoload.php')) {
throw new RuntimeException('Install dependencies to run this script.');
}
$loader = require_once $file;
$loader->add('Documents', __DIR__);
AnnotationRegistry::registerLoader([$loader, 'loadClass']);
$config = new Configuration();
$config->setProxyDir(__DIR__ . '/Proxies');
$config->setProxyNamespace('Proxies');
$config->setHydratorDir(__DIR__ . '/Hydrators');
$config->setHydratorNamespace('Hydrators');
$config->setDefaultDB('fsa');
$config->setMetadataDriverImpl(AnnotationDriver::create(__DIR__ . '/Documents'));
$dm = DocumentManager::create(null, $config);
I already tried looking at How to properly Autoload Doctrine ODM annotations? and Laravel & Couchdb-ODM - The annotation "#Doctrine\ODM\CouchDB\Mapping\Annotations\Document" does not exist, or could not be auto-loaded and a host of other threads I can't quite recall for help, but I couldn't figure out a solution.
I also tried commenting out the lines below
if ( ! file_exists($file = 'C:/path/to/vendor/autoload.php')) {
throw new RuntimeException('Install dependencies to run this script.');
}
$loader = require_once $file;
$loader->add('Documents', __DIR__);
AnnotationRegistry::registerLoader([$loader, 'loadClass']);
and ran composer dump-autoload and on command line it returned Generated autoload files containing 544 classes, but then I got the problem
[Semantical Error] The annotation "#Doctrine\ODM\MongoDB\Mapping\Annotations\Document" in class Documents\Message does not exist, or could not be auto-loaded.
So the annotations are not auto-loading, and I have no idea how to fix that.
In the model I have:
<?php
namespace Documents;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use \Doctrine\ODM\MongoDB\Mapping\Annotations\Document;
/** #ODM\Document */
class Message
{
/** #ODM\Id */
private $id;
/** #ODM\Field(type="int") */
private $sender_id;
...
I also posted a thread on github at https://github.com/doctrine/mongodb-odm/issues/1976. One commenter stated that "By default, the composer autoload file returns the autoloader in question, which seems to not be the case for you." How can I fix that? The only information I can find online is to put (inside composer.json) the lines:
"autoload": {
"psr-4": {
"Class\\": "src/"
}
},
but then what class should I be loading?
I'm very confused and being pretty new to all these tools (mongodb, yii2, etc.) doesn't help at all. I'm not sure what other information would be helpful else I would post it.
Thanks in advance.
So turns out that the problem (as was mentioned in https://github.com/doctrine/mongodb-odm/issues/1976) was that autoload.php was required twice - once in bootstrap.php and once in web/index.php (of the framework). After the require line in index.php was removed, everything worked fine.

Symfony init:acl command missing

I would like to use Symfony's ACL system but I am unable to initialize the database. I followed the steps here How to Use Access Control List (ACL's), but when I run the console command I get There are no commands defined in the "init" namespace.
I have the SecurityBundle defined in my AppKernel new Symfony\Bundle\SecurityBundle\SecurityBundle(). And here is my security.yml
# security.yml
security:
acl:
connection: default
I'm not quite understanding what I'm missing. I do understand though that it's likely a configuration issue. Looking at the Command in symfony's library I see
<?php
class InitAclCommand extends ContainerAwareCommand
{
/**
* {#inheritdoc}
*/
public function isEnabled()
{
if (!$this->getContainer()->has('security.acl.dbal.connection')) {
return false;
}
return parent::isEnabled();
}
//...
}
My guess is isEnabled() is returning false, but I'm not sure what or where I set the configuration for this.
I am using Symfony 3.1.9 and PHP7.0
Thanks
check you have the following package installed:
composer require symfony/security-acl
Try these commands:
composer require symfony/security-acl
Then:
composer update
Then run:
php bin/console init:acl
That should work

ClassNotFoundException: Attempted to load class "MongoId" from the global namespace

I am trying to install the MongoDB bundle into Symfony2. I followed Symfony documentation.
My config.yml file is:
doctrine_mongodb:
connections:
default:
server: mongodb://localhost:27017
options: {}
default_database: test_database
document_managers:
default:
auto_mapping: true
My autoload file is:
use Doctrine\Common\Annotations\AnnotationRegistry;
use Composer\Autoload\ClassLoader;
$loader = require __DIR__.'/../vendor/autoload.php';
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
use Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver;
AnnotationDriver::registerAnnotationClasses();
return $loader;
The controller and the document/product files were exactly copied from the Symfony site (I only changed the name AcmeStoreBundle to MyTestBundle).
But when I attempt to insert data, I get the following error:
ClassNotFoundException: Attempted to load class "MongoId" from the global namespace in
C:\wamp\www\MongoTest2\vendor\doctrine\mongodb-odm\lib\Doctrine\ODM\MongoDB\Id\AutoGenerator.php line 36.
Did you forget a use statement for this class?
(I cleared the cache and tried again)
Please help me to understand what's going wrong.
Install composer package alcaeus/mongo-php-adapter, because it has MongoId class. This also helped for me

Impossible to generate the table "user"

When I install FOSUserBundle (official documentation), I try to generate my table fos_user using this command:
php app/console doctrine:schema:update --force
But console returns the following message
Nothing to update - your database is already in sync with the current entity metadata
I use Symfony 2.1 and the last version to FOSUserBundle.
app/AppKernel.php contains
new FOS\UserBundle\FOSUserBundle(),
app/config/config.yml contains
fos_user:
db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
firewall_name: main
user_class: Krpano\UserBundle\Entity\User
src/Krpano/UserBundle/Entity/User.php contains
namespace Krpano\UserBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="pouet")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct()
{
parent::__construct();
// your own logic
}
}
And when I try to access to my website I have this error:
MappingException: The class 'Krpano\UserBundle\Entity\User' was not found in the chain configured namespaces FOS\UserBundle\Entity, Krpano\ServicesBundle\Entity
Can you help me?
Nothing to update - your database is already in sync with the current entity metadata
Implies that your entity is not registred because of a missing declaration in AppKernel.php.
Doctrine only search on bundle who are active.
After added the line :
new Krpano\UserBundle\KrpanoUserBundle(),
Like that:
public function registerBundles()
{
$bundles = array(
...
new Krpano\UserBundle\KrpanoUserBundle(),
new FOS\UserBundle\FOSUserBundle(),
...
); ...
Try this:
php app/console doctrine:schema:update --force
If Doctrine return:
Database schema updated successfully! "1" queries were executed
Your problem is resolve.
My answer is just a completion to Carlos Granados answer.
Add
new Krpano\UserBundle\KrpanoUserBundle(),
To your app/AppKernel.php file
I had this error and it was caused by having accidentally deleted the #ORM\Entity() line from my entity class. D'oh.
I had the same issue just like you. You missed to create yml for Doctrine Entity. This file is needed for Doctrine to generate shema in your database.
# src/Acme/UserBundle/Resources/config/doctrine/User.orm.yml
Acme\UserBundle\Entity\User:
type: entity
table: fos_user
id:
id:
type: integer
generator:
strategy: AUTO
Then in console update autoload for composer
composer dump-autoload
Then call Doctrine schema builder
php app/console doctrine:schema:update --force
Using composer.phar dump-autoload --optimize
Also provokes this error, when running:
php app/console cache:clear --env=prod --no-debug
If you run:
./composer.phar update
again it all works again.

Categories