symfony 2.3 error: autoloader find file but not class - symfony

First, sorry if my english it's not so good.
I readed a lot of questions like the one i have, but any solution works.
The question is that I'm developing a porject in Symfony 2.3, yes, i'm beginner using it...
I've created a 'Userbundle', and i want to display the info profile of an user.
When I access to the correct URL I have the famous message error:
"The autoloader expected class "Mylife\UserBundle\Entity\UserRepository" to be defined in file "D:\www\Symfony/src\Mylife\UserBundle\Entity\UserRepository.php". The file was found but the class was not in it, the class name or namespace probably has a typo."
That's my default controller code:
namespace Mylife\UserBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Mylife\UserBundle\Entity\User;
use Mylife\UserBundle\Form\Frontend\RegisterType;
class DefaultController extends Controller
{
public function profileAction(){
$user_id=1;
$em=$this->getDoctrine()->getEntityManager();
$profile=$em->getRepository('UserBundle:User')
->findProfile($user_id);
return $this->render('UserBundle:Default:profile.html.twig', array( 'profile' => $profile));
}
And my UserRepository.php code:
// src/Mylife/UserBundle/Entity/UserRepository.php
namespace Mylife\UserBundle\Entity;
use Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository
{
public function findProfile($user)
{
$em = $this->getEntityManager();
$consult= $em->createQuery('
SELECT u, nk, n
FROM UserBundle:User u
WHERE u.user= :id');
$consult->setParameter('id', $user);
return $consult->getResult();
}
}
I have the same problem when trying to use a form class in the same bundle, but i no see any error in namesapce or class name.
The project structure is:
-src
-Mylife
-UserBundle
....
-Entity
...
-User.php
-UserRepository.php
I'm going mad trying to solve the problem and reading a lot of forums and examples.
I've tryed to dissable APC, to restart Apache, erase the cache, and nothing of this worked.
Thanks a lot!!
Carlos
PD: I'm not sure why appears a piece of code at the top of the error page and why it begins in "getEntityMAnager();..." row... Why is not showing the text code before it?. Image:http://es.tinypic.com?ref=r0s8k5
IMPORTANT: When I generated the entity USer by console, I say "no" when asked to generate repository. May be this is the problem. Any suggestion now?
Thanks again

Try to add this comment in your User entity file:
/**
*
* #ORM\Entity(repositoryClass="YourProject\UserBundle\Entity\UserRepository")
*/
class User
{
...
}
or something like this:
custom repository class in symfony2

Found it!!
It's was a silly mistake. I've began the PHP repository file with
<?
...
and must be
<?php
...
Sorry at all!

Related

Load Symfony (5.2) config from database

I am a newbie in Symfony but I know how to use OOP in PHP.
I try (with frustration) to couple custom parameters with Symfony configs by using Doctrine entities.
To solve the problem I used for e.g. the answer from Michael Sivolobov: https://stackoverflow.com/a/28726681/2114615 and other sources.
My solution:
Step 1: Create new package in config folder
-> config
-> packages
-> project
-> services.yaml
-> project
-> src
-> ParameterLoaderBundle.php
-> DependencyInjection
-> Compiler
-> ParameterLoaderPass.php
Step 2: Import the new resource
# config/services.yaml
...
imports:
- { resource: 'packages/project/config/services.yaml' }
...
Step 3: Package coding
# packages/project/config/services.yaml
services:
Project\:
resource: "../src"
<?php
namespace Project;
use Project\DependencyInjection\Compiler\ParameterLoaderPass;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class ParameterLoaderBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new ParameterLoaderPass(), PassConfig::TYPE_AFTER_REMOVING);
}
}
<?php
namespace Project\DependencyInjection\Compiler;
use App\Entity\SettingCategory;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class ParameterLoaderPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$em = $container->get('doctrine.orm.default_entity_manager');
$setting = $em->getRepository(SettingCategory::class)->findAll();
$container->setParameter('test', $setting);
}
}
After at all I test the new Parameter in my API controller:
$this->getParameter('Test');
But the following error message appears:
The parameter \"test\" must be defined.
Couple of things going on here. First off, loading config from a database is very unusual in Symfony so it is not surprising that you are having difficulty. Secondly, your process code is never getting called. Part of debugging is making sure that code that you expect to be called is in fact being called. Third, you really got off on a tangent with attempting to add a bundle under config. Way back in Symfony 2 there used to be more bundle related stuff under app/config and it may be that you discovered some old articles and misunderstood them.
But, the big problem here is that Symfony has what is known as a 'compile' phase which basically processes all the configuration and caches it. Hence the CompilerPassInterface. Unfortunately, services themselves are not available during the compile phase. They simply don't exist yet so no entity manager. You need to open your own database connection if you really want to load config from a database. You will want to use just a database connection object and not the entity manager since part of the compile phase is to process the entities themselves.
So get rid of all your code and just adjust your Kernel class:
# src/Kernel.php
class Kernel extends BaseKernel implements CompilerPassInterface
{
use MicroKernelTrait;
public function process(ContainerBuilder $container)
{
$url = $_ENV['DATABASE_URL'];
$conn = DriverManager::getConnection(['url' => $url]);
$settings = $conn->executeQuery('SELECT * FROM settings')->fetchAllAssociative();
$container->setParameter('test',$settings);
}
And be aware that even if you get all this working, you will need to manually rebuild the Symfony cache after updating your settings table. It is not going to be automatic. You really might consider taking a completely different approach.

Zend\Permissions\Rbac\Role Error 500 when try to instantiate object

I'm trying to implement a RBAC in my project, but I can't instantiate Rbac class.
My code:
<?php
namespace Login\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Permissions\Rbac\Rbac;
use Zend\Permissions\Rbac\Role;
class TesteController extends AbstractActionController {
public function indexAction() {
$role = new Role('teste');
die('=== FIM ===');
}
}
When I comment the Role line it shows "=== FIM ===", but when it isn't commented it gives 500 error.
I already check the module struct in vendor and it's alright.
Do I need to do anything else when I install a vendor module via composer to zend 3 recognize it?
The error was cause by my php version that doesn't accept return type declarations. The Rbac module is full of it.

Symfony 2.5.6 error InvalidArgumentException: The service definition "event_dispatcher" does not exist

I'm trying to build my first Compiler Pass in Symfony 2. For now, I'm just trying to get the core event_dispatcher service from FrameWorkBundle inside a SampleBundle, but I get this error :
error InvalidArgumentException: The service definition "event_dispatcher" does not exist.
Here is the code for my compiler :
<?php
namespace Me\SampleBunlde\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
class RegisterListenersPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$definition = $container->getDefinition('event_dispatcher');
}
}
?>
I'm a bit surprised since I'm following step by step a professionnal Symfony book who assures me that I will find this service with that id.
I've done some researches about that, and I discovered that only the debug.event_dispatcher service was avaible. Then I checked for aliases and saw that there was a private Alias named 'event_dispatcher' pointing to debug.event_dispatcher. So I'm really confused about all that. And I'm wondering :
Why is the Alias private ? Do I need to set him Public or is it the wrong way ?
Why Symfony does not automatically interprets my event_dispatcher call ?
Thank you for your help !
Use findDefinition() instead of getDefinition(). findDefinition also looks for aliases.

Doctrine PHPCR-ODM under Symfony not detecting mapped Document class

I am attempting to integrate PHPCR-ODM with an existing Symfony project, and am having trouble getting it to (presumably) detect my mapped Document class. Specifically, I get an error like this when attempting to persist a Document of my class MyDocument:
[Doctrine\Common\Persistence\Mapping\MappingException]
The class 'Example\Common\ORM\Document\MyDocument' was not found in the chain configured namespaces Doctrine\ODM\PHPCR\Document
My class is in a potentially strange namespace because this project uses Doctrine ORM as well, and thus far I've just added a new space for mapped Documents off of that, but I can't imagine the choice of namespace name affects the functionality.
Per the docs, I have added to my app/autoload.php:
AnnotationRegistry::registerFile(__DIR__.'/../vendor/doctrine/phpcr-odm/lib/Doctrine/ODM/PHPCR/Mapping/Annotations/DoctrineAnnotations.php');
My app/config/config.yml includes the following (with parameters set in parameters.yml):
doctrine_phpcr:
session:
backend:
type: jackrabbit
url: %jackrabbit_url%
workspace: %jackrabbit_workspace%
username: %jackrabbit_user%
password: %jackrabbit_password%
odm:
auto_mapping: true
My document class lives in src/Example/Common/ORM/Document/MyDocument.php and looks like:
<?php
namespace Example\Common\ORM\Document;
use Doctrine\ODM\PHPCR\Mapping\Annotations as PHPCRODM;
/**
* #PHPCRODM\Document
*/
class MyDocument
{
/**
* #PHPCRODM\Id
*/
private $id;
/**
* #PHPCRODM\ParentDocument
*/
private $parent;
/**
* #PHPCRODM\Nodename
*/
private $name;
// .. etc
Finally, the code I am using to test the integration is inside a simple console command, and looks like:
use Example\Common\ORM\Document\MyDocument;
// ...
$documentManager = $this->container->get('doctrine_phpcr.odm.default_document_manager');
$document = new MyDocument();
$document->setParent($documentManager->find(null, '/'));
$document->setName('ExampleName');
$documentManager->persist($document);
$documentManager->flush();
I have verified that my MyDocument class is being correctly loaded, but it seems that the annotations are not being processed in a way that is making the DocumentManager aware that it is a mapped Document class.
My guess is that I have overlooked some simple configuration step, but from looking repeatedly and thoroughly at the docs for PHPCR, PHPCR-ODM, and even Symfony CMF, I can't seem to find anything. Most of the examples out there involve using PHPCR via Symfony CMF, and I wasn't able to find many (any?) real world examples of PHPCR-ODM being integrated in a regular Symfony project.
edit: The Eventual Solution
I followed the advice that #WouterJ gave below and it fixed my problem, and I further followed his suggestion of adding a compiler pass to my Symfony bundle to make this work with a non-standard namespace (i.e., something other than YourBundle\Document). In my case, this is going into a library that will be re-used elsewhere rather than a bundle, so it was appropriate.
To do this, I added a method to the src/Example/Bundle/ExampleBundle/ExampleBundle.php file like so:
<?php
namespace Example\Bundle\ExampleBundle;
use Doctrine\Bundle\PHPCRBundle\DependencyInjection\Compiler\DoctrinePhpcrMappingsPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class ExampleBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$mappedDirectories = array(
realpath(__DIR__ . '/../../Common/ODM/Document')
);
$mappedNamespaces = array(
'Example\Common\ODM\Document'
);
$phpcrCompilerClass = 'Doctrine\Bundle\PHPCRBundle\DependencyInjection\Compiler\DoctrinePhpcrMappingsPass';
if (class_exists($phpcrCompilerClass)) {
$container->addCompilerPass(
DoctrinePhpcrMappingsPass::createAnnotationMappingDriver(
$mappedNamespaces,
$mappedDirectories
));
}
}
}
That code allows any mapped document classes to be placed in the Example\Common\ODM\Document namespace and it will pick them up. This example uses annotations but the same pattern can be used for XML or YAML mappings (see the Doctrine\Bundle\PHPCRBundle\DependencyInjection\Compiler\DoctrinePhpcrMappingsPass class for method signatures).
I found that I also needed to define the doctrine_phpcr.odm.metadata.annotation_reader service for this to work, which I did in app/config.yml:
services:
doctrine_phpcr.odm.metadata.annotation_reader:
class: Doctrine\Common\Annotations\AnnotationReader
There may be a better way to do that, but that was enough to make it work for me.
The document should be placed in the Document namespace of the bundle, not the ORM\Document namespace.
If you really want to put it in the ORM\Document namespace (which is very strange, because we are talking about an ODM not an ORM), you can use the doctrine mapping compiler pass: http://symfony.com/doc/current/cookbook/doctrine/mapping_model_classes.html

Why can't load data these fixtures in Symfony2 project?

I've created a fixtures class inside my bundle's DataFixtures/ORM folder. The actual class looks like this:
use Doctrine\Common\DataFixtures\FixtureInterface,
Company\ShoppingBundle\Entity\Category;
class CategoryFixtures implements FixtureInterface
{
public function load($em)
{
$category1 = new Category()->setName("category1");
$category2 = new Category()->setName("category2");
$em->persist($category1);
$em->persist($category2);
$em->flush();
}
}
I'm not using the AbstractFixture base class, since I don't need references. I've also tried specifying the fixtures path when running the doctrine:fixtures:load console command. I'm following the official docs here.
Nothing wrong with the file naming, or my configuration: I simply forgot to put
<?php
at the top of my file :-D

Resources