Laravel string Localization in config files - php

I'm having problem using trans() function in config file, I feel it not supposed to be used that way. However I've no clue on what would be the most efficient way to translate string text in config files (files in /config folder).
Original code
<?php
return [
'daily' => 'Daily'
];
When I try to implement trans() application crashes and laravel return white page without any error messages
<?php
return [
'daily' => trans('app.daily_text')
];

The config files are one of the first stuff Laravel initialize, it means you can't use Translator nor UrlGenerator inside a config file.
I don't know what you are trying to do, but you shouldn't need to use Translator inside a config file though...

You cannot not use trans or route method inside the Laravel config file. At the time the config file is loaded, these methods are not available to run. Also, the purpose of the configuration file is used for storing pure value and we should not trigger any actions inside the configuration file.
I know sometimes you want to put things into config file with dynamic data generated from route or text from language key. In my usecase is: configure the menu structure inside the config file. On that case, you should choose the approach of: storing only the translation key and an array which include information that you can generate the URL at run time.
I put my gist here for you to look up on the approach.

You can just store the key in config file like and then use the trans function in the view to get the translations:
Config file:
<?php
return [
'foo' => 'bar'
];
Then in the view:
{{ trans(config('config.foo') }}

I don't know if this is good practice but I ended doing this in my similar situation.
Config.php:
'Foo' => array('
'route' => 'route.name',
'name' => 'translated_line', //translated in lang file ex. /en/general.php
'),
Then in the view I used:
{{ Lang::get('general.'.Config::get('foo.name'))) }}
Maybe this is too late but I posted it here anyway so that maybe someone will find it useful, like me :))

As of Laravel v5.4, you can use the __ helper function to access the translations after Laravel has booted.
Example:
config/example.php
<?php
return [
'daily' => 'Daily',
'monthly' => 'app.monthly_text',
'yearly' => 'app.yearly_text'
];
resources/lang/en/app.php
<?php
return [
'monthly_text' => 'Monthly'
];
You can access the translations like so:
<?php
// ...
$daily = config('example.daily');
$a = __($daily); // "Daily"
$monthly = config('example.monthly');
$b = __($monthly); // "Monthly"
$yearly = config('example.yearly');
$c = __($yearly); // "app.yearly_text"

Related

How to define constants that can be used across config files in Laravel 5?

As I checked on multiple sources, the Laravel way of defining constant variables is through config files. However, in my case, I want to use constants across my config files which is not possible since, as I read, it's not possible/advisable to call a config from another.
EXAMPLE
Constants:
define('THE_ID_OF_SOMETHING_NICE', 1);
define('THE_ID_OF_SOMETHING_UGLY', 2);
define('THE_ID_OF_SOMETHING_BAD', 12372);
config1.php
return [
THE_ID_OF_SOMETHING_NICE = ['many', 'nice', 'data'],
]
config2.php
return [
['many', 'nice', 'data', THE_ID_OF_SOMETHING_NICE],
]
As you can see, I just can't use the actual value of the defined constants since it'll be too unreadable. Also I don't want to clump up my .env file with these constants since it's not really meant for it.
Any workaround for this? Thanks.
P.S
Why does this so hard whilst it should be very basic principle of PHP to utilise constant definitions. CI has these figured out :/
I think you can use php include on your config.php if you don't want add a lot of to .env file. Just like that
<?php
include 'something_constant.php';
return [
THE_ID_OF_SOMETHING_NICE = ['many', 'nice', 'data'],
];
The best way to do this is to add them to the config/app.php file. Somewhere above the providers[] list you could add
'CONST' => ['THE_ID_OF_SOMETHING_NICE' => 1,
'THE_ID_OF_SOMETHING_UGLY' => 2,
],
and anywhere in the code access the values with the laravel helper config('app.CONST.THE_ID_OF_SOMETHING_NICE');
You can make use of the .env file but beware that in production, this file is ignored because the config is automatically cached. In .env you could add the line THE_ID_OF_SOMETHING_NICE=1 and in the config/app.php file you add
'CONST' => ['THE_ID_OF_SOMETHING_NICE' => env('THE_ID_OF_SOMETHING_NICE'),],
from where you can access the value just the same with the config() helper.
Personally I add the values in the app.php file and don't bother with adding values to .env, because mostly these contain non-critical information (i.e. your private keys etc)
If you'd like to create a separate file to isolate from the other config files, you could create a file f.ex. config/constants.php and return an array as it is done in other config files. Make it a flat array (no 'CONST' key). In the app/providers/AppServiceProvider in the register() method add
$this->mergeConfigFrom('config/constants.php', 'constants');
This way you can access your constants with config('constants.THE_ID_OF_SOMETHING_NICE');

Custom configuration files in CakePHP 3

I have a CakePHP 3.3.14 application where I've created 2 subdirectories, webroot/data/downloads/ and webroot/data/master
I want to put these paths in a custom configuration file and reference them in a Controller. But I can't see how to do this.
I've followed the documentation on Configuration but it's not very clear.
So what I've done:
Created config/my_config.php
The above file defines an array:
return [ 'downloadsPath' => 'webroot/data/downloads/', 'masterPath' => 'webroot/data/master/' ];
In config/bootstrap.php I've put: Configure::load('my_config', 'default');
How do I then use this in a Controller? If I put Configure::read('my_config.masterPath'); it gives an error saying: Class 'App\Controller\Configure' not found
If I add use Cake\Core\Configure; to the top of my Controller, that clears the error but the return value is null:
debug(Configure::read('my_config.masterPath')); // null
Loading another config file just extends the default App.config. So just use \Cake\Core\Configure::read('masterPath') and you are good.
EDIT
If it is your goal to have different config paths you could do it like this:
// my_config.php
return [
'MyConfig' => [
'masterPath' => '...',
...
]
];
Then use the config like this:
<?= \Cake\Core\Configure::read('MyConfig.masterPath') ?>

How show smarty template from string in yii2?

I wanna use smarty template engine in yii2.
In my project, i need load view codes from database and render them from controller.
My question is this:
Is there any way to render a view code from string and control it like common render?
i need something like below:
$this->renderAsString($templateStr, ['param1'=>$val1, 'param2'=>$val2]);
this is important for me can access variable and function like as below code in index.tpl file.
$this->render('index.tpl'['param1'=>$val1, 'param2'=>$val2]);
I read this http://www.smarty.net/docs/en/resources.string.tpl but my answer is different, i think.
There is special separate extension called yii2-smarty for rendering views with Smarty. You need to install it via Composer, then configure like this for usage:
return [
//....
'components' => [
'view' => [
'renderers' => [
'tpl' => [
'class' => 'yii\smarty\ViewRenderer',
//'cachePath' => '#runtime/Smarty/cache',
],
],
],
],
];
As for your specific problem, look at these two issues on Github:
Add ability to render view from string
View renderer from db - not implemented yet
Core developer Klimov Paul recommends to use eval, but also in Smarty dedicated function exists exactly for these kind of situations.
Example 8.4. Another {eval} example
This outputs the server name (in uppercase) and IP. The assigned
variable $str could be from a database query.
<?php
$str = 'The server name is {$smarty.server.SERVER_NAME|upper} '
.'at {$smarty.server.SERVER_ADDR}';
$smarty->assign('foo',$str);
?>
Where the template is:
{eval var=$foo}

Laravel - Is there a Global Variable?

I am using Laravel. I have referenced my project name in several different places in my views.
I then decided to change the name of my application! So is there a global variable I can use instead and then I only have to change the name in one place next time?
I looked through the docs but couldn't see this feature..
Of course global variables exist in Laravel as well. However just because the exist it doesn't mean you should use them.
A much more suitable approach would be to store the name in a config file.
You can use app/config/app.php and just add a row:
return array(
'name' => 'FooBar',
// existing values ...
'debug' => false,
'url' => 'http://localhost',
// etc ...
);
Or create your very own config file. For example app/config/site.php
return array(
'name' => 'FooBar'
);
And you use it like this:
Config::get('app.name');
Or
Config::get('site.name');
See the documentation for more information
You can make use of View Composers
http://laravel.com/docs/4.2/responses#view-composers

How to define a global variable in Laravel?

I use to develop with Drupal. In Drupal there are global variables such as $user or $_view, so you can use these in different modules. I wonder how can I make something like this in Laravel, after the user log in, I can use the global $user in different controller.Except using session is there any other ways to implement this one? Thank you.
For most constants used globally across the application, storing them in config files is sufficient. It is also pretty simple
Create a new file in the app/config directory. Let's call it constants.php
In there you have to return an array of config values.
return [
'langs' => [
'es' => 'www.domain.es',
'en' => 'www.domain.us'
// etc
]
];
And you can access them as follows
Config::get('constants.langs');
// or if you want a specific one
Config::get('constants.langs.en');
And you can set them as well
Config::set('foo.bar', 'test');

Categories