I need to get 2 entity objects from the path parameter in Symfony 3.
From the document, I can do:
/**
* #Route("/blog/{id}/comments/{comment_id}")
* #Entity("comment", expr="repository.find(comment_id)")
*/
public function showAction(Post $post, Comment $comment)
{
}
However, I could not find out where that #Entity comes from. The page return with error:
[Semantical Error] The annotation "#Entity" in method ABCBundle\Controller\ABCController::editAction() was never imported. Did you maybe forget to add a "use" statement for this annotation? in /srv/www/symfony3/src/ABCBundleController (which is being imported from "/srv/www/symfony3/src/ABCBundle/Resources/config/routing.yml").
Does anyone know?
You may want to add this use statement:
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;
See SensioFrameWorkExtraBundle at github
Related
I am using both phpstan and apidoc, but i have an error on phpstan that i can't find a way to solve or ignore.
Error message "Internal error: [Semantical Error] The annotation "#apiDefine" in class App\Controller\UserController was never imported. Did you maybe forget to add a "use" statement for this annotation?
Run PHPStan with --debug option and post the stack trace to:
https://github.com/phpstan/phpstan/issues/new?template=Bug_report.md" cannot be ignored, use excludePaths instead.
To my understanding, apidoc doesn't need any import, but when phpstan goes on my file it does not know this annotation so it triggers an error.
In my opinion the best solutions would be to ignore this kind of error, but it say:
cannot be ignored, use excludePaths instead.
But i would like to keep this file in the phpstan analyse.
How could i fix this error or ignore it ?
I wanted to ignore the annotations from api doc, but it wasn't possible. Instead I can ignore the annotations from doctrine
/**
* #IgnoreAnnotation("apiName")
* #IgnoreAnnotation("apiDefine")
* #IgnoreAnnotation("apiGroup")
* #IgnoreAnnotation("apiParam")
* #IgnoreAnnotation("apiSuccess")
*/
class UserController extends ControllerBase
The only downside that I see is the need to add it for each files.
Symfony's manual on ParamConverter has this example:
/**
* #Route("/blog/{post_id}")
* #Entity("post", expr="repository.find(post_id)")
*/
public function showAction(Post $post)
{
}
Source: http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html#fetch-via-an-expression
But using #Entity annotation gives me this error.
The annotation "#Entity" in method AppBundle\Controller\CurrencyController::currencyAction() was never imported. Did you maybe forget to add a "use" statement for this annotation?
Obviously, I need to use a namespace, but which one? Please help.
The Entity annotation only exist on master (or futur v4).
Source file here
But as you can see, this is only a shortcut to #ParamConverter annotation with expr option, so you have to use this one until next release.
Best regards.
You are trying to use ParameterConverter so this syntax is just wrong.
Use this instead
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
/**
* #Route("/blog/{post_id}")
* #ParamConverter("post_id", class="VendorBundle:Post")
*/
public function showAction(Post $post)
{
}
VendorBundle:Post should be replaced with whatever your Vendor is (if any) and Bundle is.
Using annotation #ParamConverter with option repository_method is deprecated
The repository_method option of #ParamConverter is deprecated and will be removed in 6.0. Use the expr option or #Entity.
Thus it's better to use #Entity (documentation)
You have to add the namespace :
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;
I have Silex setup with Doctrine2 ORM. I am trying to build a pagination class that I can use with my entities. I am well aware of the existing pagination classes that exist within Doctrine2 but because this project is for my school research I am trying to create this component myself.
Below is the fatal error I get when accessing this page:
Fatal error: Class 'PlayGround\Model\Helper\UserRepository' not found in D:\web\playground-solutions\vendor\doctrine\orm\lib\Doctrine\ORM\EntityManager.php on line 689
I have defined an interface called PaginateableInterface with two methods count and paginate. I went on to define a custom EntityRepository class that extends Doctrine\ORM\EntityRepository. Below is my custom EntityRepository.
<?php
namespace PlayGround\Service\Doctrine;
use Doctrine\ORM\EntityRepository as ParentEntityRepository;
class EntityRepository extends ParentEntityRepository{
public function count(){
$em = $this->getEntityManager();
$builder = $em->createQueryBuilder();
/**
* ToDo: #entity
*
* Still need to find a better way of getting entity class name.
*/
$entity = $em->getClassMetadata(get_class(__CLASS__))->getName();
//Dynamically get a count of records on any entity we happen to call this on.
$builder->select($builder->expr()->count('e'))
->from($entity, 'e');
$query = $builder->getQuery();
//Try-Catch block ommitted
return $query->getSingleScalarResult();
}
}
<?php
namespace PlayGround\Model\Helper;
use PlayGround\Service\Doctrine\EntityRepository as CustomRepository;
use PlayGround\Contract\PaginateableInterface as IPaginate;
class UserRepository extends CustomRepository implements IPaginate
{
}
In my understanding this should suffice as the count and paginate methods are sitting within the custom repository.
Inside my Paginator class I call the entity I want to paginate as shown below:
<?php
//Paginator class
$model = $this->getModel($model);
//Count should be inherited from CustomRepository aliased object.
$totalRecords = $model->count();
Below is another pierce of meet with regards to this where I add an annotation to my model to point it to the repository class it is suppose to use.
<?php
namespace Application\Model\Entity;
use Doctrine\ORM\Mapping as ORM;
use Application\Model\Entity\UserGroup;
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity
* #ORM\HasLifecycleCallbacks()
* #ORM\Entity(repositoryClass="PlayGround\Model\Helper\UserRepository")
*/
class User{ /* Rest of the code goes here... */ }
Given all this setup what could I have missed in getting this to work? I have even ran two commands on my doctrine console but that didn't help either.
Luyanda.Siko#ZACT-PC301 MINGW64 /d/web/playground-solutions
$ php app/Console/bin/doctrine.php orm:clear-cache:metadata
Clearing ALL Metadata cache entries
Successfully deleted cache entries.
Luyanda.Siko#ZACT-PC301 MINGW64 /d/web/playground-solutions
$ php app/Console/bin/doctrine.php orm:clear-cache:query
Clearing ALL Query cache entries
Successfully deleted cache entries.
EDIT:
Below is my file structure found in D:\web\playground-solutions.
You declare twice #ORM\Entity. Once with the repositoryClass and once without. Remove the one without:
#ORM\Entity
and leave this:
#ORM\Entity(repositoryClass="PlayGround\Model\Helper\UserRepository")
#ORM\HasLifecycleCallbacks should be declared without parentheses ()...
Also make sure that the EntityRepository is in the correct namespace and the corresponding folder:
your namespace is PlayGround\Model\Helper\UserRepository meaning the file should be in folder PlayGround\Model\Helper and the class file name should be UserRepository.php.
Fix and check that and if it still doesn't work leave a comment.
UPDATE:
Your UserRepository is in the wrong module. Is now in app should be in PlayGround
The file should be in:
src/PlayGround/Model/Helper/UserRepository.php
It's all about that problem.
Clearly this has really consumed my thought process. All I was doing was pointing to an incorrect namespace as pointed out by #Witt.
I changed my annotation entry in the User entity and the error went away.
<?php
/** #ORM\Entity(repositoryClass="Application\Model\Helper\UserRepository") */
Thanks you guys.
I am implementing Swagger-PHP for an API we've built.
Here is a brief recap:
Language: PHP5.3
Framework: FuelPHP 1.5.3
Environment: Local (served with Nginx)
Now I have an API method defined as follow:
/**
* #SWG\Api(
* path="/site/list",
* description="Get sites list",
* #SWG\Operation(...,
* #SWG\Parameter(...),
* #SWG\ResponseMessage(...),
* #SWG\ResponseMessage(...)
* )
* )
*/
public function action_run()
{
//doing stuff
}
I now try the following (from elsewhere in my application) to generate the JSON:
$swagger = new Swagger\Swagger('my/root/dir');
$swagger->getResource('/site/list', array('output' => 'json'));
And that first line here (when instanciating my Swagger class) is throwing me an error:
ErrorException [ User Warning ]: [Semantical Error] The class
"package" is not annotated with #Annotation. Are you sure this class
can be used as annotation? If so, then you need to add #Annotation to
the class doc comment of "package". If it is indeed no annotation,
then you need to add #IgnoreAnnotation("package") to the class doc
comment of class #Swagger\Annotations\Api.
Adding the #IgnoreAnnotation("package") is actually not helping.
I notice the error disappears if I remove the #package from here:
https://github.com/zircote/swagger-php/blob/master/library/Swagger/Annotations/Api.php#L28
But that's not a solution.
I'm guessing this is mainly Doctrine-related but I can't seem to figure it out.
Thanks for any tips or ideas on that matter.
Because FuelPHP has a Package class (in fuel/core/package.php), which isn’t an #Annotation the DocParser generates this warning.
Swagger-PHP uses the $docParser->setIgnoreNotImportedAnnotations(true) setting, which should prevent warnings like these.
I've reported the issue and fixed the problem but sadly the patch was rejected
Report the issue (again) to doctrine, the more people complain the faster it gets fixed 😉
As a workaround replace your DocParser.php with this version
We're having problems calling a certain custom entity repository function from our controller in a Symfony2 project. We have successfully done it before with other entities so we're probably missing something and I can't figure out what it could be.
Our repository class looks like this:
<?php
namespace OurSite\Bundle\OurBundle\Entity;
use Doctrine\ORM\EntityRepository;
class BlogRepository extends EntityRepository
{
public function findPreviousPosts($limit = 6)
{
$q = $this->createQueryBuilder('q')
->where('q.category = :category')
->setMaxResults($limit)
->add('orderBy', 'q.published ASC')
->getQuery();
$res = $q->getResult();
return $res;
}
}
The entity:
<?php
namespace OurSite\Bundle\OurBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* OurSite\Bundle\OurBundle\Entity\Blog
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="OurSite\Bundle\OurBundle\Entity\BlogRepository")
*/
class Blog {
// Non-relevant stuff here
}
When we call the method like this:
$em = $this->getDoctrine()->getEntityManager();
$previousPosts = $em->getRepository('OurSiteOurBundle:Blog')->findPreviousPosts();
We get this:
Undefined method 'findPreviousPosts'. The method name must start with either findBy or findOneBy!
If we do echo get_class($em->getRepository('OurSiteOurBundle:Blog')); it outputs BlogRepository, as expected.
What could be causing the problem? We have a superfluous bundle directory in the project but I'm guessing that can't be causing it?
From the source you provided, this may not be your issue, but it may save others some search time.
I was coming across the same "must start with either findBy or..." error, and it turns out in my Entity definition I had accidentally made a call to the #ORM\Entity annotation Twice. The first time I used it properly and set the repositoryClass, but the second time I just used it by itself (as with an Entity that wouldn't have a custom repository) and so that overwrote the previous repositoryClass definition.
/**
*
* #ORM\Entity(repositoryClass="Company\TestBundle\Entity\MyEntityRepository")
* #ORM\Table(name="testing_my_entity")
* #ORM\Entity
*/
class MyEntity
{
etc...
}
If you get this error: The method name must start with either findBy or findOneBy! that means that your custom repository isn't loaded.
Check for typos in the code, clear cache, make sure "OurSiteOurBundle" is the actual shortcut name.
I had the same problem. I've seen many posts about that but nothing solved it.
Finally I found out that was because I was previously using generated yml files, so Doctrine didn't read annotations for mapping !
So just be sure you don't have any yml/xml Doctrine files.
And then :
app/console doctrine:cache:clear-metadata
Did you used this entity before? I see strange entity shortcut for Blog
OurSiteOurBundle:Blog
but your Blog have OurSite\ Bundle\OurBundle\Entity namespace. I think it should be
OurSiteBundleOurBundle:Blog
and entity manager points you to wrong repository class
If use xml for mapping(pass tested):
Update xml or yml mapping file, add repository-class attribute:
<entity name="Ccd\Bundle\FrontendBundle\Entity\UvUpdatePageContent" table="uv_update_page_content" **repository-class="Ccd\Bundle\FrontendBundle\Entity\UvUpdatePageContentRepository"**>
http://doctrine-mongodb-odm.readthedocs.org/en/latest/cookbook/mapping-classes-to-orm-and-odm.html
Then update doctrine cache:
php app/console doctrine:cache:clear-metadata
use yml(not tested):
Acme\DemoBundle\Entity\Post:
type: entity
table: posts
RepositoryClass: Acme\DemoBundle\Entity\PostRepository