Symfony2 multiple Environments - php

I was wondering if there is any possibility to define multiple environments in Symfony's app.php?
src/web/app.php:
$kernel = new AppKernel('benchmark', false);
$kernel = new AppKernel('benchmark,dev', false); // < Incl. the dev tools
Why do I ask? Isn't this a stupid question? Because the default check syntax seems to support multiple environments in_array() or do I misinterpret something here?
src/app/AppKernel.php:
if (in_array($this->getEnvironment(), array('dev'))) {
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
...
}

The "check" in the app/AppKernel is here to check if there are some bundles you want available in several environments, such as "test" or "dev" for example.
you could then have in your AppKernel following lines :
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new My\Bundle\Uber\MyUberBundle();
...
}
that will enable this example bundle in both dev and test environments.
So the app.php doesn't support multiple environment definitions. If you want several envs you can still define new files as app.php and app_dev.php :)
For example an admin.php with itself look something like
<?php
use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\HttpFoundation\Request;
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('admin', false);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Related

Using Symfonys dump in production

I used the dump function within one of our applications and our client got used to it during development (tbh I didn't know that it won't work in prod). Now the application is going live which means no more debug mode - and no more dump function.
Is there any way to enable the dump function during prod?
Despite weird will of use dump() in production env...
If I am not mistaken dump() is from DebugBundle which is enabled only in dev and test env.
public function registerBundles()
{
$bundles = [
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new AppBundle\AppBundle(),
];
if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
if ('dev' === $this->getEnvironment()) {
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
$bundles[] = new Symfony\Bundle\WebServerBundle\WebServerBundle();
}
}
return $bundles;
}
As you can see above DebugBundle is registered only in previous mentioned envs. Probably moving it out of the if will allow you to use dump() in production.
You have to indeed add this line to AppKernel.php:
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
But also change this boolean in app.php from false to true:
$kernel = new AppKernel('prod', true); // true is replacing false, in second argument here
Tested for Symfony 4.4 and works.
Read Symfony documentation 🧐, function 'dump()' is part of 'VarDumper' component, it's a dev dependency, so if you want to use it in prod you need to install it as required dependency:
❌ $ composer require --dev symfony/var-dumper
βœ” $ composer require symfony/var-dumper
🚨 But I guess it's not a good practice use it in production, it could show sensitive information.

Symfony error: Class 'Symfony\Component\HttpKernel\Kernel' not found

After upgrading from Symfony 3.1 to 3.2 I get this error message :
Fatal error: Class 'Symfony\Component\HttpKernel\Kernel' not
found in /var/www/html/HeliosBlog/app/AppKernel.php on line 6
Here's what my app/autoload.php looks like:
<?php
use Doctrine\Common\Annotations\AnnotationRegistry;
if (!$loader = #include __DIR__.'/../vendor/autoload.php') {
$message = <<< EOF
EOF;
if (PHP_SAPI === 'cli') {
$message = strip_tags($message);
}
die($message);
}
// intl
if (!function_exists('intl_get_error_code')) {
require_once __DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs/functions.php';
$loader->add('', __DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs');
}
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
return $loader;
Here's what my app_dev.php file looks like:
<?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !(in_array(#$_SERVER['REMOTE_ADDR'], array(
'127.0.0.1',
'fe80::1', '::1')) || php_sapi_name() === 'cli-server')
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require __DIR__.'/../app/autoload.php';
Debug::enable();
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
//$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
And here's what my AppKernel.php looks like:
<?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new JMS\AopBundle\JMSAopBundle(),
new JMS\DiExtraBundle\JMSDiExtraBundle($this),
new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
new JMS\SerializerBundle\JMSSerializerBundle(),
new Helios\BlogBundle\HeliosBlogBundle(),
new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
new Helios\UserBundle\HeliosUserBundle(),
new FOS\UserBundle\FOSUserBundle(),
new FOS\ElasticaBundle\FOSElasticaBundle(),
new Knp\Bundle\MarkdownBundle\KnpMarkdownBundle(),
new Helios\ManagerBundle\HeliosManagerBundle(),
new FOS\JsRoutingBundle\FOSJsRoutingBundle(),
//new Avalanche\Bundle\ImagineBundle\AvalancheImagineBundle(),
new Oneup\UploaderBundle\OneupUploaderBundle(),
new Gregwar\CaptchaBundle\GregwarCaptchaBundle(),
new Sonata\AdminBundle\SonataAdminBundle(),
new Sonata\DoctrineORMAdminBundle\SonataDoctrineORMAdminBundle(),
new Sonata\BlockBundle\SonataBlockBundle(),
new Sonata\CoreBundle\SonataCoreBundle(),
new Knp\Bundle\MenuBundle\KnpMenuBundle(),
new HWI\Bundle\OAuthBundle\HWIOAuthBundle(),
new Ivory\CKEditorBundle\IvoryCKEditorBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
$bundles[] = new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle();
$bundles[] = new CoreSphere\ConsoleBundle\CoreSphereConsoleBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
}
Already tried removing the vendor folder and doing a composer install.
Any ideas?
I was able to solve it by simply adding
require_once __DIR__.'/autoload.php';
to app/console before
require_once __DIR__ . '/AppKernel.php';`
Ran into the same error. Found that the bootstrap.php.cache was unaware of the Kernel class.
This happened due the Sensio Distibution bundle having an update.
For this I posted an issue which can be found here:
https://github.com/sensiolabs/SensioDistributionBundle/issues/302
I hope this helps others as well.
I had this issue while running composer update, because it was still using app/console (probably outdated) instead of the new bin/console.
I fixed this issue by:
removing app/console file.
creating a var/ folder in my project root directory - see this answer for explanation.
I run into this problem as well while updating my project from Symfony 2.x (can't remember whether it was 2.7 or 2.8) to 3.2. In turn out that the problem was caused by the app/console file. I believe the problem is caused by the way I created the project ages ago.
To solve this problem, I copied the app/console file from another project which I successfully upgraded to 3.2. I am not sure whether there will be some other problems down the line, but at least I got rid of this error.
The discussion that prompted me to make this change is https://github.com/symfony/symfony/issues/16713

Symfony 2 ESI Cache

I have an action which is called in all my page (for logged people only), this action retrieves recent tweets from my twitter account.
API access is limited so I would like the result of this action to be in cache for 10 minutes
public function socialAction(){
$consumerKey = $this->container->getParameter('consumer_key');
$consumerSecret = $this->container->getParameter('consumer_secret');
$accessToken = $this->container->getParameter('access_token');
$accessTokenSecret = $this->container->getParameter('access_token_secret');
// on appel l'API
$tweet = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
$screen_name = "blabla";
$tweets = $tweet->get('statuses/user_timeline', [
'screen_name' => $screen_name,
'exclude_replies' => true,
'count' => 50
]);
$tweets = array_splice($tweets, 0, 5);
$response = $this->render('GestionJeuBundle:Default:social.html.twig', array("tweets" => $tweets));
$response->setPublic();
$response->setSharedMaxAge(600);
return $response;
}
To enable caching I have made ​​the following changes
app/config/config.yml
framework:
esi: { enabled: true }
fragments: { path: /_proxy }
and
app/AppCache.php
<?php
require_once __DIR__.'/AppKernel.php';
use Symfony\Bundle\FrameworkBundle\HttpCache\HttpCache;
class AppCache extends HttpCache
{
protected function getOptions()
{
return array(
'debug' => false,
'default_ttl' => 0,
'private_headers' => array('Authorization', 'Cookie'),
'allow_reload' => false,
'allow_revalidate' => false,
'stale_while_revalidate' => 2,
'stale_if_error' => 60,
);
}
}
and
web/app_dev.php
<?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !in_array(#$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '.....', 'fe80::1', '::1'))
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/../app/AppKernel.php';
require_once __DIR__.'/../app/AppCache.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$kernel = new AppCache($kernel);
// When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter
Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
error_log($kernel->getLog());
Despite that the page is updated every page refresh (after testing, it does exactly the same things in production environment with change on app.php too)
Have I misunderstood or forgotten a thing ?
Thank you in advance for your help.
EDIT solve : i was rendering this action with
{{render(controller("GestionJeuBundle:Default:social")) }}
changing it for
{{render_esi(controller("GestionJeuBundle:Default:social")) }}
solve my problem
Hexune
i was rendering this action with
{{render(controller("GestionJeuBundle:Default:social")) }}
changing it for
{{render_esi(controller("GestionJeuBundle:Default:social")) }}
solve my problem
As far as I experimented last weeks, it's worth noting that if you use debug environment in Symfony, Varnish always passes-by your request to the back-end.

Can't get Symfony 2 toolbar to display on website

I am trying to do this from a remote computer so the app_dev.php is:
<?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
After the template renders I get this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Title</title>
</head>
<body>
<h1>Give us a toolbar now will you?</h1>
</body>
</html>
Looks like valid html and has a body element but no tool bar is there.
I have only ftp access so renamed the Symfony/app/cache folder to gone.
I have confirmed that app_dev.php executes Debug::enable(); and $kernel = new AppKernel('dev', true); (adding an error there causes an error.
I have confirmed that valid html is produced rendering index.html.twig (not a cached one). I have renamed the cache directory.
Not sure what else to check to have it show the tool bar.
You must enable the profiler in AppKernel.php
public function registerBundles()
{
$bundles = ...
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
...
}
return $bundles;
}
And make sure that you have JavaScript enabled.

How should the app.php looks like for APC and Symfony 2.1

I would like to preapare the app.php file with Symfony 2.1 and APC. I took the Symfony standard edition configured it with doctrine and then made changes described here:
http://symfony.com/doc/2.1/book/performance.html
<?php
require_once __DIR__.'\..\vendor\symfony\symfony\src\Symfony\Component\ClassLoader\UniversalClassLoader.php';
require_once __DIR__.'\..\vendor\symfony\symfony\src\Symfony\Component\ClassLoader\ApcUniversalClassLoader.php';
use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\HttpFoundation\Request;
$loader = new ApcClassLoader('sf2', $loader);
$loader->register(true);
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
?>
but it is not working, I got error:
Fatal error: Class 'Symfony\Component\HttpKernel\Kernel' not found in __my_path__\app\AppKernel.php on line 7
How should I prepare the app.php for best performance.
Take a look at the default app.php file in the Symfony Standard Distribution. In order to enable APC your app.php file should look like this:
use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\HttpFoundation\Request;
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
// Use APC for autoloading to improve performance.
// Change 'sf2' to a unique prefix in order to prevent cache key conflicts
// with other applications also using APC.
$loader = new ApcClassLoader('sf2', $loader);
$loader->register(true);
require_once __DIR__.'/../app/AppKernel.php';
//require_once __DIR__.'/../app/AppCache.php';
$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
//$kernel = new AppCache($kernel);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
You can also improve performance if you enable the symfony gateway cache by uncommenting the require_once __DIR__.'/../app/AppCache.php'; and $kernel = new AppCache($kernel); lines.

Categories