I'm using gettext translations for SF2 and I arrange my translation files in different folder structure than the normal bundle (I kind of created my own mini plugin system for some specific needs).
In any case, this is how I'm loading my translation files:
$finder = new Finder();
$finder->files()->filter(function (\SplFileInfo $file)
{
return 2 === substr_count($file->getBasename(), '.') && preg_match('/\.\w+$/', $file->getBasename());
})->in($dirs);
foreach ($finder as $file) {
// filename is domain.locale.format
list($domain, $locale, $format) = explode('.', $file->getBasename(), 3);
// we have to add resource right away or it will be too late
$translator->addResource($format, (string)$file, $locale, $domain);
}
It works well, the only problem is that it is not cached which is not very efficient. I wonder what I should do instead to cache these translation?
My problem was that I forgot the declare translator in the config file and thus the translation pass doesn't work
framework:
translator: { fallback: %locale% }
Related
I have a section within my site where the user can upload their own profile pictures which is stored in the output directory and tracked in the database like so:
$form = $this->createForm(ProfileUpdateForm::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$user = $this->getUser();
$firstname = $form->get('firstname')->getData();
$lastname = $form->get('lastname')->getData();
$picture = $form->get('profilepicture')->getData();
if($picture == null)
{
$user
->setFirstName($firstname)
->setLastName($lastname);
}
else
{
$originalFilename = pathinfo($picture->getClientOriginalName(), PATHINFO_FILENAME);
// this is needed to safely include the file name as part of the URL
$safeFilename = strtolower(str_replace(' ', '', $originalFilename));
$newFilename = $safeFilename.'-'.uniqid().'.'.$picture->guessExtension();
try {
$picture->move(
'build/images/user_profiles/',
$newFilename
);
} catch (FileException $e) {
$this->addFlash("error", "Something happened with the file upload, try again.");
return $this->redirect($request->getUri());
}
// updates the 'picture' property to store the image file name
// instead of its contents
$user
->setProfilePicture($newFilename)
->setFirstName($firstname)
->setLastName($lastname);
}
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash("success", "Your profile was updated!");
return $this->redirectToRoute('account');
}
return $this->render('account/profile.html.twig', [
'profileform' => $form->createView()
]);
That issue I've found is that every time I compile my (local) project, the image is then deleted (because the public/build directory gets built by deleting and creating again).
If I'm not mistaken, isn't that how deployments work too? And if so, is that the right way to upload an image? What's the right way of going about this?
I'm not sure why, but your public/ directory shouldn't be deleted.
If you're using Webpack Encore, then public/build/ content is deleted and created again when you compile assets. But not public/ itself.
For uploads, we create public/upload/ directory.
Then, most of the time, we set some globals, which allow us to save the file name only.
Globals for Twig in config/packages/twig.yaml which "root" will be in your public/ directory
twig:
globals:
app_ul_avatar: '/upload/avatar/'
app_ul_document: '/upload/document/'
And globals for your controllers, repositories, etc in config/services.yaml
parameters:
app_ul_avatar: '%kernel.root_dir%/../public/upload/avatar/'
app_ul_document: '%kernel.root_dir%/../public/upload/document/'
It's handy because, as I just said, you only get to save the file name in the database.
Which mean that, if you got a public/upload/img/ folder, and want to also generates thumbnails, you can then create public/upload/img/thumbnail/ and nothing will change in your database, nor do you have to save an extra path.
Just create a new global app_ul_img_thumbnail, and you're set.
Then all you have to do is call your globals when you need them, and contact with the file name:
In Twig:
{{ app_ul_avatar~dbResult.filename }}
Or in Controller:
$this->getParameter('app_ul_avatar').$dbResult->getFilename();
NelmioApiDocBundle is allowing only single configuration file as .yml as.
nelmio_api_doc:
routes:
path_patterns: # an array of regexps
- ^/api
documentation:
paths:
/api/login_check:
...
/api/refresh_token:
...
But I have more then 200 URL to use and all for different Bundles.
it would working properly but hard to handle all in same file.
So if anyone has solution to divide "paths" as different separate files.
I can't see the config options "routes" and "documentation" in the configuration reference of NelmioApiDocBundle
You should instead use Annotations, as described in the docs.
Problem solved! :-)
One of Mine friend has a great idea to resolve this problem. actually, this is not the proper solution, but I this is the only way to solve this problem.
We create "api_index.yaml"
export_path: '/config/packages/api_doc.yaml'
import_paths:
- "#DomCoreBundle/Resources/config/api_doc/api_base_doc.yaml"
- "#DomCmsBundle/Resources/config/api_doc/static_page_path_doc.yaml"
- "#DomEntityBundle/Resources/config/api_doc/category_path_doc.yaml"
- "#DomCmsBundle/Resources/config/api_doc/carousel_path_doc.yaml"
- "#DomQuickLinkBundle/Resources/config/api_doc/quick_link_path_doc.yaml"
- "#DomUserBundle/Resources/config/api_doc/user_path_doc.yaml"
- "#DomUserBundle/Resources/config/api_doc/dealer_path_doc.yaml"
...
Then we create a Symfony command(script) which read each "import_paths" file and append content in "export_path" file.
$this->io = new SymfonyStyle($input, $output);
$path = $this->kernel->locateResource('#FaCoreBundle/Resources/config/api_index.yaml');
$paths = Yaml::parse(file_get_contents($path));
if (array_key_exists('import_paths', $paths)) {
$contentLength = $this->loadFilesByPath($input, $output, $paths);
if ($input->getOption('watch')) {
$contentLengthNew = [];
while (true) {
foreach ($paths['import_paths'] as $path) {
$ymlPath = $this->kernel->locateResource($path);
$contentLengthNew[$ymlPath] = md5((file_get_contents($ymlPath)));
}
if (!empty(array_diff($contentLength, $contentLengthNew)) || count($contentLength) != count($contentLengthNew)) {
$diff = array_diff($contentLengthNew, $contentLength);
if (!empty($diff)) {
$this->io->writeln(sprintf('<comment>%s</comment> <info>[file+]</info> %s', date('H:i:s'), current(array_keys($diff))));
}
$contentLength = $this->loadFilesByPath($input, $output, $paths);
}
sleep($input->getOption('period'));
}
}
}
A simply way is to read yaml files from a not autoload area, merge the content and write a single file that will be loaded.
SF 4.x
/config
/NELMIOApiDocDefinitions // out of autowire
/one.yaml
/two.yaml
/packages
/_NELMIOApiDocDefinitions.yaml // file_put_content()
one.yaml
nelmio_api_doc:
areas:
path_patterns:
- /one
documentation:
tags:
- { name: One, description: '...' }
paths:
/onepath/:
...
Kernel.php
protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader)
{
$this->mergeNELMIOApiDocYamlDefinitions();
...
}
private function mergeNELMIOApiDocYamlDefinitions()
{
// dev, prod, ...
$kernelEnvironnement = $this->getEnvironment();
// No need to rebuild definitions in production
if ($kernelEnvironnement == 'prod')
return;
// Path to the configuration directory
$confDir = $this->getProjectDir() . '/config';
// Path to the documentations files to merge
$yamlDefinitionsDirectory = $confDir . '/NELMIOApiDocDefinitions';
// Get the files to merge (without dots directories)
$yamlDefinitionsFiles = array_diff(scandir($yamlDefinitionsDirectory), ['.', '..']);
// Read definitions files and merge key with theirs values
$mergedDefinitions = [];
foreach ($yamlDefinitionsFiles as $yamlDefinitionFile) {
$yamlFileContent = Yaml::parseFile($yamlDefinitionsDirectory . '/' . $yamlDefinitionFile);
$mergedDefinitions = array_merge_recursive($mergedDefinitions, $yamlFileContent);
}
// Build the YAML
$yaml = Yaml::dump($mergedDefinitions);
// Write the YAML into a single file to be loaded by Symfony
file_put_contents($confDir . '/packages/_NELMIOApiDocDefinitions.yaml', $yaml);
}
Problem solved with
config/packages/nelmio.yaml
imports:
- {resource: '../nelmio/default.yaml'}
- {resource: '../nelmio/v1.yaml'}
config/nelmio/default.yaml
nelmio_api_doc:
areas:
default:
path_patterns: [ ^/default/ ]
documentation:
info:
title: Default
config/nelmio/v1.yaml
nelmio_api_doc:
areas:
default:
path_patterns: [ ^/v1/ ]
documentation:
info:
title: V1
I know that the basis of Silex approach in which all the application logic in a single file. But my application will be possible to have more than twenty controllers. So I want to have a handy map to manage the router.
My question is to search for solutions in which I would be able to make a router to a separate file. In the best case, the file must be of YAML type:
# config/routing.yml
_home:
pattern: /
defaults: { _controller: MyProject\Controller\MyController::index }
But the native is also a good case (for me):
$routes = new RouteCollection();
$routes->add(
'home',
new Route('/', array('controller' => 'MyProject\Controller\MyController::index')
));
return $routes;
Problem of the second case is that I have to use the match() function for each rule of routing. It is not at all clear.
What are the ways to solve this issue? The condition is that I want to use the existing API Silex or components of Symfony2.
Small note:
I don't use a ControllerProviderInterface for my Controller classes. This is an independent classes.
First of all, the basis of Silex is not that you put everything in one file. The basis of Silex is that you create your own 'framework', your own way of organizing applications.
"Use silex if you are comfortable with making all of your own architecture decisions and full stack Symfony2 if not."
-- Dustin Whittle
Read more about this in this blogpost, created by the creator of Silex.
How to solve your problem
What you basically want is to parse a Yaml file and get the pattern and defaults._controller settings from each route that is parsed.
To parse a Yaml file, you can use the Yaml Component of Symfony2. You get an array back which you can use to add the route to Silex:
// parse the yaml file
$routes = ...;
$app = new Silex\Application();
foreach ($routes as $route) {
$app->match($route['pattern'], $route['defaults']['_controller']);
}
// ...
$app->run();
I thought I'd add my method here as, although others may work, there isn't really a simple solution. Adding FileLocator / YamlFileLoader adds a load of bulk that I don't want in my application just to read / parse a yaml file.
Composer
First, you're going to need to include the relevant files. The symfony YAML component, and a really simple and useful config service provider by someone who actively works on Silex.
"require": {
"symfony/yaml": "~2.3",
"igorw/config-service-provider": "1.2.*"
}
File
Let's say that your routes file looks like this (routes.yml):
config.routes:
dashboard:
pattern: /
defaults: { _controller: 'IndexController::indexAction' }
method: GET
Registration
Individually register each yaml file. The first key in the file is the name it will be available under your $app variable (handled by the pimple service locator).
$this->register(new ConfigServiceProvider(__DIR__."/../config/services.yml"));
$this->register(new ConfigServiceProvider(__DIR__."/../config/routes.yml"));
// any more yaml files you like
Routes
You can get these routes using the following:
$routes = $app['config.routes']; // See the first key in the yaml file for this name
foreach ($routes as $name => $route)
{
$app->match($route['pattern'], $route['defaults']['_controller'])->bind($name)->method(isset($route['method'])?$route['method']:'GET');
}
->bind() allows you to 'name' your urls to be used within twig, for example.
->method() allows you to specify POST | GET. You'll note that I defaulted it to 'GET' with a ternary there if the route doesn't specify a method.
Ok, that's how I solved it.
This method is part of my application and called before run():
# /src/Application.php
...
protected function _initRoutes()
{
$locator = new FileLocator(__DIR__.'/config');
$loader = new YamlFileLoader($locator);
$this['routes'] = $loader->load('routes.yml');
}
Application class is my own and it extends Silex\Application.
Configuration file:
# /src/config/routes.yml
home:
pattern: /
defaults: { _controller: '\MyDemoSite\Controllers\DefaultController::indexAction' }
It works fine for me!
UPD:
I think this is the right option to add collections:
$this['routes']->addCollection($loader->load('routes.yml'));
More flexible.
You could extend the routes service (which is a RouteCollection), and load a YAML file with FileLocator and YamlFileLoader:
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Routing\Loader\YamlFileLoader;
$app->extend('routes', function($routeCollection) {
$locator = new FileLocator([__DIR__ . '/../config']);
$loader = new YamlFileLoader($locator);
$collection = $loader->load('routes.yml');
$routeCollection->addCollection($collection);
return $routeCollection;
});
You will need symfony/config and symfony/yaml dependencies though.
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');
}