Laravel 5 - Config sub-folder - php

In Laravel 5, we can read a config value via this:
config('app.url')
But, how can we read config file value in the sub-folder? I have tried with config('subfolder/app.url') but it didn't work.

You can do like this in laravel 5 config('subfolder.myfile.var'); subfolder is folder name , myfile is your file name and var is your variable.

I've created: config/local/app.php containing:
<?php
return [
"key" => "value"
];
and using artisan, here's what i got:

Create Folder with name subfolder inside config directory create file app.php
Inside app.php put all your constants
return array(
'APP_URL' => 'http://www.test.com/xyz',
'APP_MAX_FOLDER_SIZE' => 1000000000,
);
and access like
config('subfolder.app.APP_URL');
it is advisable to create constants in Upper case letter and create file name that makes sense like constans.php or appconstants.php etc

for Lumen developers
Just in case someone need it. This is the way I was able to do it:
Step 1 - Create the sub directory under config/ for example validator
Step 2 - Create the configuration files: messages.php, rules.php
config
└── validator
├── messages.php
└── rules.php
Step 3 - Enable the configuration files under bootsrap/app.php
/*
|--------------------------------------------------------------------------
| Register Custom Configuration
|--------------------------------------------------------------------------
|
| Register custom configuration files that are under config/
|
*/
$app->configure('validator/messages');
$app->configure('validator/rules');
/**/
$app->router->group([
'namespace' => 'App\Http\Controllers',
], function ($router) {
require __DIR__.'/../routes/web.php';
});
return $app;
Step 4 - Get the configuration
config('validator/rules.key');
ref: https://laracasts.com/discuss/channels/lumen/config-in-subdirectory

Related

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') ?>

Using vinkla/hashids package in Laravel 5.2

I am using vinkla/hashids and i have followed the following steps
composer require vinkla/hashids
Add the service provider to config/app.php in the providers array
If you want you can use the facade. Add the reference in config/app.php to your aliases array.
php artisan vendor:publish this step does not create hashid.php in config file
use Vinkla\Hashids\Facades\Hashids;
Hashids::encode(4815162342);
And i get error that hashids class not found
It seems that the provider is not booting.
Try to do this:
php artisan config:clear
php artisan clear-compiled
The first will clear any cached config files, and the later will clear the services cache.
It worked for me, hope it works for you too.
I found the solution here: Laravel 5.2 Service provider not booting
Try checking inside your $laravelSite/config Directory to see if you find a file called hashids.php...
In your Controller; try also to import the the Hashids Class manually like so:
<?php
namespace App\Http\Controllers;
use Vinkla\Hashids\Facades\Hashids;
class SampleClass extends {
public function testHashID(){
$h1 = Hashids::encode(4815162342);
var_dump($h1);
$h2 = Hashids::decode('oaobgb-rnar');
var_dump($h2);
}
}
And by the way; if you don't see hashids.php within your $laravelSite/config Directory; you may try to manually create it. The file just returns an array of Configuration Settings... the content to the file looks like so:
/*
* This file is part of Laravel Hashids.
*
* (c) Vincent Klaiber <hello#vinkla.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
return [
/*
|--------------------------------------------------------------------------
| Default Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the connections below you wish to use as
| your default connection for all work. Of course, you may use many
| connections at once using the manager class.
|
*/
'default' => 'main',
/*
|--------------------------------------------------------------------------
| Hashids Connections
|--------------------------------------------------------------------------
|
| Here are each of the connections setup for your application. Example
| configuration has been included, but you may add as many connections as
| you would like.
|
*/
'connections' => [
'main' => [
'salt' => 'your-salt-string',
'length' => 'your-length-integer',
'alphabet' => 'your-alphabet-string',
],
'alternative' => [
'salt' => 'your-salt-string',
'length' => 'your-length-integer',
'alphabet' => 'your-alphabet-string',
],
],
];
To encode just do this
\Hashids::encode($characters)
And to decode
\Hashids::decode($characters)

Change the storage path in Laravel 5

I want to change the Laravel 5.1 storage path: something like /home/test/storage. This has the advantage that these files are not stored in the repository, which is fairly ugly I think.
In Laravel 4, this was very simple with bootstrap/paths.php.
In Laravel 5, it works by using $app->useStoragePath('/path/') in bootstrap/app.php. However, I want to define the storage path with a config option, like $app->useStoragePath(config('app.storage_path'). The config option calls an environment variable or returns a default location.
Doing this results in a Uncaught exception 'ReflectionException' with message 'Class config does not exist'; this makes sense, because this function is not loaded yet.
I tried setting the storage path just after booting:
$app->booted(function () use ($app) {
$app->useStoragePath(config('app.storage_root'));
});
This changed nothing. I also tried directly binding it to path.storage:
$app->bind('path.storage', function ($app) {
return config('app.storage_root');
});
The last option works partially; the view cache is now placed in the correct location, but the logs are still at the old location.
Set it up in .env
app.php
'app_storage' => env('APP_STORAGE', storage_path()),
app/Providers/AppServiceProvider.php
public function register()
{
$this->app->useStoragePath(config('app.app_storage'));
}
.env
APP_STORAGE=custom_location
Laravel 5.3 is in bootstrap/app.php
/*
|--------------------------------------------------------------------------
| Set Storage Path
|--------------------------------------------------------------------------
|
| This script allows us to override the default storage location used by
| the application. You may set the APP_STORAGE environment variable
| in your .env file, if not set the default location will be used
|
*/
$app->useStoragePath( env( 'APP_STORAGE', base_path() . '/storage' ) );
Here is a simple solution of changing the storage path in Laravel 5 like we do in Laravel 4
on bootstrap/app.php
# new storage path
# base_path() -> returns root path
$path_storage = base_path() . "../../storage";
# override already $app->storagePath using the function
$app->useStoragePath($path_storage);
this will make the storage path to be same with the session, views, cache, logs
This works on Laravel 5.2
File: app/Providers/AppServiceProvider.php
public function register() {
...
$this->app->useStoragePath(config('what_ever_you_want'));
...
}
Calling useStoragePath on your AppServiceProvider wouldn't do the job properly because the AppServiceProvider is called after the config files are loaded. so any use of storage_path in config files would still refer to the old storage path.
In order to properly solve this problem I suggest you extend Application class and then on the constructor of your own class write the followings.
/**
* MyApplication constructor.
*/
public function __construct($basePath = null)
{
parent::__construct($basePath);
// set the storage path
$this->afterLoadingEnvironment(function () {
$this->useStoragePath(/*path to your storage directory*/);
});
}
if your website is hosted;
move everything from public folder to root folder
$app->bind('path.public', function() {
return __DIR__;
});
add this code in your bootstrap/app.php :
$app->useStoragePath(__DIR__ . '/../custom-path/');
and in config/filesystem.php :
'local' => [
'driver' => 'local',
'root' => storage_path('everything'), //custom-path/everything
],
'public' => [
'driver' => 'local',
'root' => storage_path(''),
'url' => env('APP_URL'),
'visibility' => 'public',
],
and then run php artisan config:cache
This works on Laravel 5.8 because you have to load the environment variables before you try to use them.
File: bootstrap/app.php
$app->afterLoadingEnvironment(function() use ($app) {
$app->useStoragePath(env('APP_STORAGE', storage_path()));
});

How to manually add classmap in Laravel 4.2?

i'm using laravel 4.2
I have 2 application folders namely 'app' and 'backend':
I edited bootstrap/start.php so that when i access www.site1.com/backend it will go to 'backend' application. Hence, it will go to the 'app'.
// override app folder to backend
if (defined('ENVIRONMENT') && ENVIRONMENT == 'backend')
{
$path_settings['app'] = __DIR__.'/../backend';
$path_settings['storage'] = __DIR__.'/../backend/storage';
}
I want to add a specific classmaps when I access /backend. I don't want to edit composer.json and add classmap there. How can I programattically do that?
You can try to use Composer's ClassLoader directly. Something like this:
$loader = new \Composer\Autoload\ClassLoader();
// PSR-0
$loader->add('My\Backend', __DIR__.'/../backend');
// PSR-4
$loader->addPsr4(....);
// class map
$loader->addClassMap(...);
// activate the autoloader
$loader->register();
In your file config/view.php add :
'paths' => [
realpath(base_path('backend'))
],

Setting aliases in Yii2 within the app config file

I'm trying to set an alias in Yii2 but I'm getting a Invalid Parameter / Invalid path alias for the below code that is placed in the app config file:
'aliases' => [
// Set the editor language dir
'#editor_lang_dir' => '#webroot/scripts/sceditor/languages/',
],
If I remove the # it works.
I noticed you can do this:
Yii::setAlias('#foobar', '#foo/bar');
...but I would prefer to set it within the app config file. Is this not possible? If so, how?
Yii2 basic application
To set inside config file, write this inside $config array
'aliases' => [
'#name1' => 'path/to/path1',
'#name2' => 'path/to/path2',
],
Ref: http://www.yiiframework.com/doc-2.0/guide-structure-applications.html
But as mentioned here,
The #yii alias is defined when you include the Yii.php file in your entry script. The rest of the aliases are defined in the application constructor when applying the application configuration.
If you need to use predefined alias, write one component and link it in config bootstrap array
namespace app\components;
use Yii;
use yii\base\Component;
class Aliases extends Component
{
public function init()
{
Yii::setAlias('#editor_lang_dir', Yii::getAlias('#webroot').'/scripts/sceditor/languages/');
}
}
and inside config file, add 'app\components\Aliases' to bootstrap array
'bootstrap' => [
'log',
'app\components\Aliases',
],
In config folder create file aliases.php. And put this:
Yii::setAlias('webroot', dirname(dirname(__DIR__)) . '/web');
Yii::setAlias('editor_lang_dir', '#webroot/scripts/sceditor/languages/');
In web folder in index.php file put:
require(__DIR__ . '/../config/aliases.php');
Before:
(new yii\web\Application($config))->run();
If run echo in view file:
echo Yii::getAlias('#editor_lang_dir');
Show like this:
C:\OpenServer\domains\yii2_basic/web/scripts/sceditor/languages/
#webroot alias is not available at this point, it is defined during application bootstrap :
https://github.com/yiisoft/yii2/blob/2.0.3/framework/web/Application.php#L60
No need to define this alias yourself, you should simply use another one :
'aliases' => [
// Set the editor language dir
'#editor_lang_dir' => '#app/web/scripts/sceditor/languages/',
],
To improve on #vitalik_74's answer
you can place it in config/web.php instead(if you are using the basic yii app, I'm not sure about the main config file in the advance version, but the same applies, just put the require on the main config file) so that it gets shorten to:
require(__DIR__ . '/aliases.php');

Categories