Symfony 2 (2.3.x) Annotation Route not working - symfony

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.

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

Symfony 3.4. Not any route is working - No route found for "GET /

My Symfony 3.4 project does not recognize any route anymore. Debugging routes in terminal (php bin/console debug:router) does show all the routes but app_dev.php keeps giving error messages. Routing is enabled and set correct in routing.yml file.
Clearing cache also did not work.
mail_chimp:
resource: "#MailChimpBundle/Controller/"
type: annotation
prefix: /
/**
* #Route("/klanten/lijst")
*/
public function klantenLijstAction() {
return;
}
screenshot
Thanks.
> the routing tries to match routes one by one in the order of their definitions; whenever one matches, work is done.
In the routes-list image, you look to have three (maybe more) routes to answer the URL '/'. Which single one should run a controller action?
You should probably set prefixes for the URLs that aren't the index route.

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.

Assetic Route Not Found

I have a twig extension whose purpose is to collect a list of CSS and JS file paths given to it by function calls throughout a template hierarchy and then at the end of the twig template to take the output buffer and include these files in the <head> section of the page. For the most part it has been straightforward to implement.
In my service definition for the twig extension I am injecting the assetic.helper.dynamic service into it. The problem is when I call the javascripts() or stylesheets() method to get a URL for a CSS or JS file I get an error like this:
An exception has been thrown during the rendering of a template ("None
of the chained routers were able to generate route: Route
'_assetic_bd311c7' not found")
service.yml:
admin.twig.asset_extension:
class: Zing\Delta\AdminBundle\Twig\AssetExtension
tags:
- { name: twig.extension }
arguments: ['#assetic.helper.dynamic']
In my extension I am essentially doing this to get the URL for an asset:
$assetic_helper->stylesheets(array(
'#SomeBundle/Resources/public/js/jquery.tablesort.min.js'
));
I don't understand why the router can't find the routes or why assetic is setting up the routes.
The fix ended up being to run the following commands in the following order from the project root.
$ php app/console assets:install
$ php app/console assetic:dump
$ php app/console cache:clear

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