This post is dedicated to the easy solution that seems to exist to add your own namespaces, the solution with the loader in app/autoload.php.
There is a lot of documentations talking about the magic methods like registerNamespace or registerPrefix.
The problem is that those methods exist for a UniversalClassLoader object.
I downloaded the Symfony standard edition 2.2, and the app/autoload.php looks more like that (pretty much the same with Symfony standard edition 2.1) :
use Doctrine\Common\Annotations\AnnotationRegistry;
$loader = require __DIR__.'/../vendor/autoload.php';
// intl
if (!function_exists('intl_get_error_code')) {
require_once __DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs/functions.php';
}
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
return $loader;
the loader used in fact is the composer loader. The only method you could use is the 'add' method like this if you hope to add 'seculibs/collections' namespace for example:
$loader->add("seculibs\\collections", __DIR__.'/../vendor/seculibs/collections/');
But it does not seem to work : when I execute programm I have the same classNotFound for /seculibs/collections/xx.php
So I changed the autoload.php like that :
require_once ('/../vendor/symfony/symfony/src/Symfony/Component/ClassLoader/UniversalClassLoader.php');
use Doctrine\Common\Annotations\AnnotationRegistry;
use Symfony\Component\ClassLoader\UniversalClassLoader;
$loader = require __DIR__.'/../vendor/autoload.php';
$universalLoader = new UniversalClassLoader();
$universalLoader->registerNamespace("seculibs\\collections", __DIR__.'/../vendor/seculibs/collections/');
$universalLoader->register();
// intl
if (!function_exists('intl_get_error_code')) {
require_once __DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs/functions.php';
}
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
return $loader;
Nothing...
But obviously it works for a lot of persons so.. what am I doing wrong ? Do they have some other Symfony version that would be found on secret websites ?
one of the classes is like that :
namespace seculibs\collections;
class LinkedMap {
private $items;
public function __construct() {
$this->items = array();
}
public function __destruct() {
unset($this->items);
}
....
$loader->add('seculibs\\collections',__DIR__ . '/../vendor');
new LinkedMap();
Assuming you have file: vendor/seculibs/collections/LinkedMap.php
Normally, you would have another level in your library. Something like:
vendor/MyStuff/seculibs/collections
And then the add line would point to vendor/MyStuff
You can add your own libraries to the composer.json autoload config, so even though they aren't loaded by composer, they will be in the generated autloader.
"autoload": {
"psr-0": {
"": "src/",
"MyLib_": "/home/sites/MyLib"
}
},
Related
A so far working bundle now needs its own configuration file inside the projects using the bundle, to manage bundle settings individually.
However, no matter which approach I use (the old one before Symfony 6.1 nor the new one extending AbstractBundle) there is - at no time - any new .yaml-File created inside the projects ./config/packages/ directory.
This is my code (the old style, prior to Symfony 6.1, extending Bundle):
Bundle Class
mycorpforms/src/MyCorpFormsBundle.php
<?php
namespace MyCorp\FormsBundle;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Definition\Configurator\DefinitionConfigurator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class MyCorpFormsBundle extends Bundle
{
// empty
}
Configuration
mycorpforms/src/DependencyInjection/Configuration.php
<?php
namespace MyCorp\FormsBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface
{
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('mycorp_forms');
$treeBuilder->getRootNode()
->children()
->booleanNode('favorite_submenu_enabled')->defaultFalse()->end()
->end()
;
return $treeBuilder;
}
}
Extension
mycorpforms/src/DependencyInjection/MyCorpFormsExtension.php
<?php
namespace MyCorp\FormsBundle\DependencyInjection;
use Knp\Bundle\SnappyBundle\DependencyInjection\Configuration;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
class MyCorpFormsExtension extends Extension
{
public function load(array $configs, ContainerBuilder $containerBuilder)
{
$loader = new YamlFileLoader(
$containerBuilder,
new FileLocator(__DIR__.'/../../config/packages')
);
$loader->load('mycorp_forms.yaml');
$configuration = new Configuration();
$processor = new Processor();
$config = $processor->processConfiguration($configuration, $configs);
$containerBuilder->setParameter('mycorp_forms.favorite_submenu_enabled', $config['favorite_submenu_enabled']);
}
}
Yaml
Additionally I added the desired mycorp_forms.yaml inside the bundles ./config/packages/ dir.
This is the actual file required in the projects:
mycorpforms/config/packages/mycorp_forms.yaml
mycorp_forms:
# Enable Favorite-Sub-Menu (Requires Knp-Snappy-Bundle !)
favorite_submenu_enabled: false
The bundle installs flawlessly in any of my projects, however no mycorp_forms.yaml file is created. Obviously this requires symfony/flex which is so far required by the bundle itself.
Q: What do I miss here?
Q: How can this yaml-file automatically be added when the bundle is installed?
I read the documentation up and down numerous times, but to be honest, I get more confused every time.
Thank you very much for any help or explanation!
This requires Symfony Flex
To have a .yaml config file being generated/updated automatically, there is 2 possible ways:
public bundle: register it in the public recipe repository
private bundle: set up your own private flex recipe repository
I am trying to add Symfony 5.4 to my legacy project. There is a pretty nice documentation on how to do this, but there's a big problem - the documentation assumes "normal" Symfony, but each time I try to install Symfony using their recommended way of composer create-project, I get a Symfony version with symfony/runtime - the big problem here, is that this version has a completely different index.php:
<?php
use App\Kernel;
require_once dirname(_DIR_).'/vendor/autoload_runtime.php';
return function (array $context) {
return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
};
The documentation found here is based on a completely different index file.
I did find that I can remove the runtime package, and just copy old index, and it works for the most part, but then you also have problems with console.php and I worry that if I go this route there will be more and more problems caused by my installation expecting symfony/runtime and me manually removing it's
I tried installing Symfony 5.3 as well as different patches of 5.4, all came with this installed, even though I did work on some 5.3 / 5.4 projects and had the old school index.php file.
Does anyone know how to currently install Symfony with the "old" index.php, console.php etc.?
Thanks!
So the task is to migrate from a non-Symfony legacy app to a Symfony app. The basic idea is to allow the Symfony app to process a request and then hand it off to the legacy app if necessary. The Symfony docs show how to do this but but relies on the older style index.php file. The newer runtime based approach is a bit different.
But in the end all it really takes is a couple of fairly simple classes. A runner class takes care of creating a request object and turning it into a response. This is where you can add the bridge to your legacy app. It's a clone of Symfony's HttpKernelRunner class:
namespace App\Legacy;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\TerminableInterface;
use Symfony\Component\Runtime\RunnerInterface;
class LegacyRunner implements RunnerInterface
{
private $kernel;
private $request;
public function __construct(HttpKernelInterface $kernel, Request $request)
{
$this->kernel = $kernel;
$this->request = $request;
}
public function run(): int
{
$response = $this->kernel->handle($this->request);
// check the response to see if it should be handed off to legacy app
dd('Response Code ' . $response->getStatusCode());
$response->send();
if ($this->kernel instanceof TerminableInterface) {
$this->kernel->terminate($this->request, $response);
}
return 0;
}
}
Next you need to wire up runner by extending the SymfonyRuntime::getRunner method:
namespace App\Legacy;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Runtime\RunnerInterface;
use Symfony\Component\Runtime\SymfonyRuntime;
class LegacyRuntime extends SymfonyRuntime
{
public function getRunner(?object $application): RunnerInterface
{
if ($application instanceof HttpKernelInterface) {
return new LegacyRunner($application, Request::createFromGlobals());
}
return parent::getRunner($application);
}
}
Finally, update composer.json to use your legacy runtime class:
"extra": {
...
"runtime": {
"class": "App\\Legacy\\LegacyRuntime"
}
}
After updating composer.json do a composer update for the changes to take effect and start your server. Navigate to a route and you should hit the dd statement.
I'm trying to implement the GeocodableBehavior on a Symfony 1.4 (with Propel 1.6) project i'm working on, but until now it's a complete failure. I've tried to search if other people but I didn't found anything, like if I was the only one having troubles with this.
So, maybe I'm missing something very very easy, but following the instructions given on the GeocodableBehavior leads to nothing but errors, and I can't figure out where's the problem.
I followed instructions for the GeocodableBehavior (here -> http://www.propelorm.org/cookbook/geocodable-behavior.html)
This seems to work as i'm getting the latitude/longitude columns created on my model. Until then, it works fine.
Where things get a little more complicated is when trying to save an object with the GeocodableBehavior, there's problems with the Geocoder class.
(Documentation here -> https://github.com/willdurand/Geocoder)
My class is Point, referring to a geolocated point, an address. When creating a Point using sf admin generator, the behavior which is supposed to use some fields (street, postal_code, country, etc) to query the GoogleMaps api, just fails to use the Geocoder class.
Fatal error: Class 'Geocoder\Geocoder' not found in /var/www/vhosts/www._________.local/lib/model/om/BasePoint.php on line 3717
I put the Geocoder class in a lib/vendor/geocoder folder, I tried to use the autoload.yml file to load it, but nothing changes...
autoload:
geocoder:
name: geocoder
path: %SF_LIB_DIR%/vendor/geocoder
recursive: on
There's something i'm missing in how to load those classes in my sf project, and i can't find what. Geocoder package has an autoload.php file but i didn't manage to "load" it successfully...
Thanks in advance.
I know it's kinda giving up on the autoloader, but you could establish a register function in /config/ProjectConfiguration.class.php. The only downside is that you will need to add a call to the function before any block that uses Geocoder.
class ProjectConfiguration extends sfProjectConfiguration
{
static protected $geocoderLoaded = false;
static public function registerGeocoder()
{
if (self::$geocoderLoaded) {
return;
}
require_once sfConfig::get('sf_lib_dir') . '/vendor/geocoder/autoload.php';
self::$geocoderLoaded = true;
}
...
}
Then just execute ProjectConfiguration::registerGeocoder(); anywhere you'd need the class. It's more annoying than getting the autoloader to work, but it's at least dependable.
Did you check your autoload cache to see it there is something related to Geocoder?
/cache/[apps_name]/dev/config/config_autoload.yml.php
/cache/project_autoload.cache
Maybe, manually add the autoload in the /config/ProjectConfiguration.class.php:
class ProjectConfiguration extends sfProjectConfiguration
{
public function setup()
{
require_once sfConfig::get('sf_lib_dir').'/vendor/geocoder/src/autoload.php';
Using the built-in autoloader should be a working option, but you can also combine symfony's autoloader with a "PSR-0 enabled" one. Basically, this boils down to the following implementation:
public function setup()
{
// plugin stuff here
// register the new autoloader
spl_autoload_register(array($this, 'autoloadNamespace'));
}
public function autoloadNamespace($className)
{
$className = ltrim($className, '\\');
$fileName = '';
$namespace = '';
if ($lastNsPos = strripos($className, '\\'))
{
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
// make sure that the path to Geocoder is correct
foreach(array(
sfConfig::get('sf_lib_dir').'/vendor/Geocoder/src' . DIRECTORY_SEPARATOR . $fileName . $className . '.php',
) as $fileName)
{
if (file_exists($fileName))
{
require $fileName;
return true;
}
}
return false;
}
With this additional autoloader, your application should be able to use Geocoder.
I want to make a local config file, config_local.yml, that allows each development environment to be configured correctly without screwing up other people's dev environments. I want it to be a separate file so that I can "gitignore" it and know that nothing essential is missing from the project, while simultaneously not having the issue of git constantly telling me that config_dev.yml has new changes (and running the risk of someone committing those changes).
Right now, I have config_dev.yml doing
imports:
- { resource: config_local.yml }
which is great, unless the file doesn't exist (i.e. for a new clone of the repository).
My question is: Is there any way to make this include optional? I.e., If the file exists then import it, otherwise ignore it.
Edit: I was hoping for a syntax like:
imports:
- { resource: config.yml }
? { resource: config_local.yml }
I know this is a really old question, and I do think the approved solution is better I thought I would give a simpler solution which has the benefit of not changing any code
You can use the ignore_errors option, which won't display any errors if the file doesn't exist
imports:
- { resource: config_local.yml, ignore_errors: true }
Warning, if you DO have a syntax error in the file, it will also be ignored, so if you have unexpected results, check to make sure there is no syntax error or other error in the file.
There is another option.
on app/appKernel.php change the registerContainerConfiguration method to this :
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
$extrafiles = array (
__DIR__.'/config/config_local.yml',
);
foreach ($extrafiles as $filename) {
if (file_exists($filename) && is_readable($filename)) {
$loader->load($filename);
}
}
}
this way you have a global config_local.yml file that overwrites the config_env.yml files
A solution is to create a separate environment, which is explained in the Symfony2 cookbook. If you do not wish to create one, there is another way involving the creation of an extension.
// src/Acme/Bundle/AcmeDemo/DepencendyInjection/AcmeDemoExtension.php
namespace Acme\DemoBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
class AcmeDemoExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
// All following files will be loaded from the configuration directory
// of your bundle. You may change the location to /app/ of course.
$loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
try
{
$loader->load('config_local.yml');
}
catch(\InvalidArgumentException $e)
{
// File was not found
}
}
}
Some digging in the Symfony code revealed me that YamlFileLoader::load() FileLocator::locate() will throw \InvalidArgumentException, if a file is not found. It is invoked by YamlFileLoader::load().
If you use the naming conventions, the extension will be automatically executed. For a more thorough explanation, visit this blog.
I tried both above answers but none did work for me.
i made a new environment: "local" that imports "dev", but as you can read here: There is no extension able to load the configuration for "web_profiler" you also had to hack the AppKernel class.
Further you couldnt set config_local.yml to .gitignore because the file is necessary in local env.
Since i had to hack the AppKernel anyway i tried the approach with the $extrafiles but that resulted in "ForbiddenOverwriteException"
So now what worked for me was a modification of the $extrafiles approach:
replace in app/AppKernel.php
$loader->load(__DIR__ . '/config/config_' . $this->getEnvironment() . '.yml');
with
if ($this->getEnvironment() == 'dev') {
$extrafiles = array(
__DIR__ . '/config/config_local.yml',
);
foreach ($extrafiles as $filename) {
if (file_exists($filename) && is_readable($filename)) {
$loader->load($filename);
}
}
} else {
$loader->load(__DIR__ . '/config/config_' . $this->getEnvironment() . '.yml');
}
I need to use PHPExcel with a Symfony2 project. Anyone know how to set up the project correctly to use the library? Should i put it in the vendor directory? What should be changed in the configuration files etc?
Actually, to do it right you need to follow next steps:
Edit your deps file and add dependency from the PHPExcel
[PHPExcel]
git=http://github.com/PHPOffice/PHPExcel.git
target=/phpexcel
version=origin/master
Run php bin/vendors install in order to install all missing dependencies (PHPExcel in our case)
Update prefixes section in app/autoload.php:
$loader->registerPrefixes(array(
// ...
'PHPExcel' => __DIR__.'/../vendor/phpexcel/Classes',
));
Done. Now, you can use it in your bundle's controller (code based on PHPExcel example from Tests/01simple-download-xls.php):
<?php
namespace Demo\MyBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use PHPExcel;
use PHPExcel_IOFactory;
class DemoController extends Controller
{
public function demoAction()
{
$response = new Response();
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Me")
->setLastModifiedBy("Someone")
->setTitle("My first demo")
->setSubject("Demo Document");
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B2', 'world!')
->setCellValue('C1', 'Hello')
->setCellValue('D2', 'world!');
// Set active sheet index to the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel5)
$response->headers->set('Content-Type', 'application/vnd.ms-excel');
$response->headers->set('Content-Disposition', 'attachment;filename="demo.xls"');
$response->headers->set('Cache-Control', 'max-age=0');
$response->prepare();
$response->sendHeaders();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit();
}
}
Copy the library to your vendors directory.
Configure autoloader in your bootstrap file:
$loader->registerPrefixes(array(
// Swift, Twig etc.
'PHPExcel' => __DIR__ . '/../vendor/phpexcel/lib/PHPExcel'
));
That's all.
actually the best solution is to use https://github.com/liuggio/ExcelBundle.
I tried to use #Crozin's solution but I was still getting an error about IOFactory::createWriter.
Hope this helps,
Simone
As of Symfony 2.3, you can now do this:
...
"require": {
...
"phpoffice/phpexcel": "dev-master"
...
},
...
Then just run composer update and dependencies will resolve automatically.
Or you can do composer require phpoffice/phpexcel:dev-master if you don't want to mess with the composer.json file.
If you are using composer to manage your project, you can just change the composer.json file:
"autoload": {
"psr-4": {
"": "src/",
"": "vendor/phpoffice/phpexcel/Classes/"
},
"classmap": [
"app/AppKernel.php",
"app/AppCache.php"
]
},
Then add
use PHPExcel;
use PHPExcel_IOFactory;
to your controller file, and you can use the PHPExcel like this:
$objPHPExcel = new PHPExcel();
Hope it helps.
With composer (since Symfony2.1) it's really easy, you only have to modify the composer.json.
You don't need to register the namespace anymore!
Only two things, to notice:
refer to github tags, I only found a soltion with the package type
when changing something in the composer.json related to the class autoloading stuff, you have to remove the whole directory in the vendor dir
Here is the related link: use PHPExcel with composer and Symfony2.2