PhpStorm Doesn't Recognize Doctrine Entity Classes - symfony

PhpStorm doesn't seem to recognize any of my Doctrine entity classes or their methods.
$comment = $em->getRepository('MyBundle:Comment')->findOneBy(array('id' => $id));
$comment->getId();
/* PHPSTORM THROWS WARNING: Method getId() not found in subject class */
The error goes away, only when I explicitly comment it - which really clutters my controller.
/* #var \MyBundle\Entity\Comment $comment */
$comment = $em->getRepository('MyBundle:Comment')->findOneBy(array('id' => $id));
Is there a way to document this for PhpStorm in my Entity Class?
I'm using the Symfony2 plugin with PhpStorm 8. Thanks!

I had this issue. Magically solved by clearing the Doctrine metadata:
php app/console doctrine:cache:clear-metadata
EDIT: In GitHub reposiory of the symfony plugin there is a brief description on what to do when this issue happens:
https://github.com/Haehnchen/idea-php-symfony2-plugin
Autocomplete (or something else) is not working! Help!
[...]
Many features require the
app/cache/dev/appDevDebugProjectContainer.xml file to exist. It is
generated when you boot your app in dev environment (open /app_dev.php
in a browser or php app/console).
Since my server is remote, manually synchronizing the file app/cache/dev/appDevDebugProjectContainer.xml solved my problem.
When I was working on a local server, instead, the command I wrote above helped me to make autocomplete work again.

I have the same problem with the Symfony2 Plugin, this is maybe not a nice solution but it works
/** #var EntityManager $em */
$em = $this->doctrine->getManager();

your issue should be fixed, now. there was a problem on multiple getRepository implementations of proxy classes in cache folder. just update to >= 0.11.81

Now, I prefer declaring repositories as services so you don't have those typehint problems:
services:
MyBundle\Entity\CommentRepository:
class: MyBundle\Entity\CommentRepository
public: true
factory: ['#doctrine', getRepository]
arguments:
- MyBundle\Entity\Comment
Then in your controller :
use MyBundle\Entity\CommentRepository;
$comment = $this->get(CommentRepository::class)->findOneBy(['id' => $id]);

Try to invalidate caches of PhpStorm. Go to file->Invalidate caches

Related

PDO Exception: An exception occurred in driver: could not find driver for mysql

I know it is frequently asked question. But I reviewed and read all of it. Unfortunately I could not find a correct answer for my problem. I am using symfony. I followed the instruction and tutorial on https://symfony.com/doc/current/doctrine.html. all steps went perfectly. I run the following commands in terminal without any problem:
composer require symfony/orm-pack
composer require --dev symfony/maker-bundle
php bin/console doctrine:database:create
php bin/console make:entity
php bin/console make:migration
php bin/console doctrine:migrations:migrate
php bin/console make:controller ProductController
with the above commands I could create a database, ProductEntity, a table for Product
Till this point I suppose that the connection to my database runs perfectly.
Then in ProductController I used the Code on the symfony website:
// src/Controller/ProductController.php
namespace App\Controller;
// ...
use App\Entity\Product;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Response;
class ProductController extends AbstractController
{
/**
* #Route("/product", name="create_product")
*/
public function createProduct(): Response
{
// you can fetch the EntityManager via $this->getDoctrine()
// or you can add an argument to the action: createProduct(EntityManagerInterface $entityManager)
$entityManager = $this->getDoctrine()->getManager();
$product = new Product();
$product->setName('Keyboard');
$product->setPrice(1999);
$product->setDescription('Ergonomic and stylish!');
// tell Doctrine you want to (eventually) save the Product (no queries yet)
$entityManager->persist($product);
// actually executes the queries (i.e. the INSERT query)
$entityManager->flush();
return new Response('Saved new product with id '.$product->getId());
}
}
It gives Error: Driver not found like in the picture
I have checked database url in env, it works without problem (I created a database and product table through it). I checked phpinfo and pdo_mysql is enabled without problem.
I have tested database connection with fixature following the instruction here https://symfony.com/doc/current/testing/database.html and was successful without problem
Can you please help me?
Thanks to guillaumesmo, I used symfony php -m. Here I saw the error unable to load pdo_mysql library. I remembered, that I have 2 PHP Versions installed on my system.
I updated the PHP Version to PHP 7.4.1 and deleted the older versions. It works perfectly. I didn't understand why could I connect and update my database via Terminal and Fixature but not with EntityManagerInterface. Anyhow I works now

JMS Serializer: overriding default naming strategy in symfony 4 has no effect

I found this thread proposing a neat way of overriding globally the default naming strategy in config.yml
but this is for symfony 3 and I am on symfony 4 so I added the line to my config > packages > jms_serializer.yaml but this has no effect at all.
jms_serializer:
visitors:
xml_serialization:
format_output: '%kernel.debug%'
property_naming:
id: 'jms_serializer.identical_property_naming_strategy'
Does anyone understand why ?
I do dependency injection of SerializerInterface $serializer to use the serializer as it is not possible to call the service from AbstractController in SF4. Controller is deprecated in SF4.
Try removing var/cache manually. When I cleared cache with cache:clear command it didn't work, but after I cleaned it manually it did!
I hope this solution will help you too.
Add jms_serializer.camel_case_naming_strategy.class: JMS\Serializer\Naming\IdenticalPropertyNamingStrategy to your parameters configuration.

SYMFONY3 in prod look for TWIG template in wrong folder instead of custom bundle indicated in routing.yml and AppKernel.php

I am implementing a SYMFONY 3 project in production mode for the first time.
I follow OceanDigital tutorial and the standard doc.
I went thru a bunch of issues linked to user writing rights that I've solved, and I do get now a SYMFONY ERROR page (one step closer to victory) with this message:
Unable to find template "MyBundle:std_page:home.html.twig" (looked
into: /[folder to symf project]/app/Resources/views,
/[folder to symf project]/vendor/symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form,
/[folder to symf project]/vendor/knplabs/knp-menu/src/Knp/Menu/Resources/views).
If I look in my [my symf project]\app\config\routing.yml, I have:
my_bundle:
resource: "#MyBundle/Resources/config/routing.yml"
options:
expose: true
In [my symf project]\app\AppKernel.php, in the registerBundles() function, I have:
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = [
....
new MyBundle\MyBundle(),
.....
]
}
}
And the file regarding the template that should be fetched [my symf project]\src\MyBundle\Ressources\views/std_page/home.html.twig exists.
What did I not set up right, in production mode, to have it looking for the TWIG template in the folder [my symf project]\src\MyBundle\Ressources\views/?
After some search it happens to be a mistake similar to the one described in that SO thread.
In my controller I had:
return $this->render('MyBundle:Std_page:home.html.twig',$parameters);
Instead of:
return $this->render('MyBundle:std_page:home.html.twig',$parameters);
The development was made on a WINDOWS 10 OS, and it is set up in production on a UBUNTU 16.04. It seems that UBUNTU is stricter than WINDOWS regarding the letter case.

Symfony 2 (2.3.x) Annotation Route not working

I'm new on symfony and I'm following this tutorial:
http://it.siciarek.pl/docs/references/howtostart.html
At some point at the end of the installation process (after getting rid of ACME) I've created a new Bundle
php app/console generate:bundle --bundle-name=AgcoukMainBundle --namespace=Agcouk/MainBundle --dir=src --format=annotation --structure --no-interaction
my DefaultController looks like:
namespace Agcouk\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
class DefaultController extends Controller
{
/**
* #Route("/", name="home")
* #Template()
*/
public function indexAction()
{
return array();
}
}
and my routing.yml (app/config/routing.yml)
agcouk_main:
resource: "#AgcoukMainBundle/Controller/"
type: annotation
prefix: /
Now, trying to access the page sf2/ (sf2/config.php works!) I get a 404 Error.
I've even debugged the routes via console (php app/console router:debug home) and everything looks fine to me
[router] Route "home"
Name home
Path /
Host ANY
Scheme ANY
Method ANY
Class Symfony\Component\Routing\Route
Defaults _controller: Agcouk\MainBundle\Controller\DefaultController::indexAction
Requirements NO CUSTOM
Options compiler_class: Symfony\Component\Routing\RouteCompiler
Path-Regex #^/$#s
(I've tried even to specify the Controller file name in the routing.yml and nothing changes, even the debug gives the same result).
Any clue?
Thanks
First of all you should use Symfony's Official Documentation... www.symfony.com
This tutorial you are following are even writing the framework's name wrong: "Symphony", so maybe is out of date or something.
And have you tried to clear your cache? php app/console cache:clear --env=dev
Inspired by this post:
symfony2 - how to switch from "dev" to "prod"?
I've finally solved the issue. I've manually deleted the files in app/cache/dev and app/cache/prod and then I've changed the owner of the prod cache folder
sudo chown www-data app/cache/prod
now, pointing at my virtual host (sf2) the page is loaded with no 404 Error.

Force configuration reload in Symfony2

I have a script which makes changes to the Symfony2 configuration and needs to be made aware of the new configuration before proceeding (specifically adding dbal connections). Is there a way to force the reload of the configuration during script execution?
Update: You can't reload the configuration, but you can set the parameters on-the-fly, see second "Update" paragraph
It's not really possible in Symfony2 to do that.
In production mode, everything (even the configuration) is cached, so you have to clear the cache with
app/console cache:clear --env=prod --no-debug
(maybe followed by a app/console cache:warmup --env=prod --no-debug)
to reload the configuration. In development mode you could experiment with shutdown() followed by a boot() from Symfony\Component\HttpKernel\Kernel or maybe loadClassCache - but all of this is not really that what you want.
What exactly changes are made to the configuration files? Maybe you should use different files for different environments or consider any other method to get those changes (via a simple Webservice or even a static file read from within a Controller).
Update:
I figured out that you can set your container configuration parameter on-the-fly via
$container->setParameter('parameter', value);
Have a look at the Symfony2 documentation.
My answer probably arrives very late but could be useful to someone else.
Symfony cache for "prod" environment is stored in "app/cache/prod/" folder and contains many things (Twig templates translated in PHP in "twig/" subfolder, annotations in "annotations/" subfolder, and... configuration parameters, app*ProjectContainer.php files, among many other things).
So what you can do is: when your configuration script changes parameters.yml, it can also delete appProdProjectContainer.php. The next user to hit your Symfony app will face a little longer response time, but the new configuration parameter will be taken into account and cached.
Here is the partial solution, besides I used it in Symfony 3.2, but nevertheless this code is used to reload bundle configuration on the fly.
Firstly, you should inject container instance inside the service / controller where you want to use bundle instance which was reinitialized with other config:
/**
* Service constructor.
*
* #param ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$container = ReinitializedBundleExtension::updateContainerWithProdConfiguration($container);
}
Secondly, you should add a method to ReinitializedBundleExtension class which will update the container with reinitialized bundle instance and dependencies:
/**
* Updates container with bundle services resolved with production configuration.
*
* #param ContainerInterface $oldContainer
*
* #return ContainerInterface $container
*/
public static function updateContainerWithProdConfiguration(ContainerInterface $oldContainer)
{
$containerBuilder = new ContainerBuilder();
// Copy external services used in the bundle.
$logger = $oldContainer->get('logger');
$containerBuilder->set('logger', $logger);
// Load the production config files.
$bundleResourcesPath = $oldContainer->get('kernel')->locateResource('#ReinitializedBundle/Resources/');
$fileLocator = new FileLocator($bundleResourcesPath . '/config');
$loader = new Loader\YamlFileLoader($containerBuilder, $fileLocator);
$loader->setResolver(new LoaderResolver([$loader]));
$loader->load($bundleResourcesPath . 'config/production/services.yml');
// Resolving bundle services with prduction config.
$containerBuilder->compile();
$containerBuilder->resolveServices($containerBuilder->getDefinitions());
// Merge resolved prod-configured services with old container.
$serviceIds = $containerBuilder->getServiceIds();
foreach ($serviceIds as $serviceId) {
// Services which are not related to the bundle.
if (strpos($serviceId, 'reinitialized_bundle_config_prefix') === false) {
continue;
}
$oldContainer->set($serviceId, $containerBuilder->get($serviceId));
}
return $oldContainer;
}
PS:
1. All the ReinitializedBundle params and services are marked with 'reinitialized_bundle_config_prefix' prefix, so it's easy to recognize them in container, i.e:
reinitialized_bundle_config_prefix.service1
reinitialized_bundle_config_prefix.param1
This is a solution for Yaml configs, so YamlFileLoader was used.
ReinitializedBundle config filestructure:
.ReinitializedBundle
└── Resources
└── config
├── production
| ├─── services.yml
| └─── other stuff
└── staging
├─── services.yml
└─── other stuff

Resources