how to set common code once in YII - php

i wanted to know in which file we can set common code, for example i wanted to set timezone to UTC, instead of putting same code in all controllers file is there any way to put the code once and it will be reflect in all files.

You may create your file in ''components'' folder. You can see this folder in "protected" folder.
Or you can write your code in controller.php
File path: webroot/protected/components/Controller.php

Can you please try to add the codes in bootstrap.php file
If you need to set the server time you can check here.It is a simple method
Change time zone

Use application params, ie:
// config part
return array(
// ...
'params' => array(
'myParam' => 123
)
// ...
);
// Then in app use
Yii::app()->params['myParam'] // Will return 123
You can also create your own params holder as component, ie:
// config part
'components' => array(
'myConfigs' => array(
'class' => 'ext.MyConfigs'
'myParam1' => 123,
'myParam2' => 'blah'
)
)
// Component in extensions
class MyConfigs extends CComponent
{
public $myParam1;
public $myParam2 = 'defaultValue';
}
// Then in app use it:
Yii::app()->myConfigs->myParam1 // will return 123

Related

Having constants for all pages in Laravel

I want to have some constants to have IP, platform, browser to be placed in a single file and to be used in all views and controllers like so:
// inside app/config/constants.php
return [
'IP' => 'some ip'
];
// inside controller
echo Config::get('constants.IP');
But instead of 'some ip', I want to use Request::ip() at least or even better, to use parse_user_agent()['platform'] that its code link is here
Simply you may put something like this in your config file:
return [
'ip' => app('request')->ip()
];
I use a little customized one for my sitewise configs, for example, let's say you want to use something like this:
/**
* Get config/constants.php
*
* [
* 'person' => [
* 'name' => 'Me',
* 'age' => 1000
* ]
* ];
*/
$name = constants('person.name');
So, to achieve this you need to write a function like:
// Helpers/Common.php
function constants($key = null)
{
$constants = config('constants');
return is_null($key) ? $constants : array_get($constants, $key);
}
Now, in your composer.json file you may add the following files entry:
"psr-4": {
"App\\": "app/"
},
"files": ["Helpers/Common.php"]
Then you need to add the constants.php in config directory for example:
<?php
return [
"ip" => app('request')->ip(),
"person" => [
"name" => "Sheikh Heera",
"age" => 10000
],
];
Finally, just run composer-dump from terminal and you are done. So, if the ip key is available in the array then you may just try this:
$ip = constants('ip');
From the view (Blade), you may use following to echo out the ip:
{{ constants('ip') }}
Let's sum up the whole process:
Create a directory in your project root (or inside app if you wish) as Helpers.
Create the Common.php file in that directory and put the array (return it)
Put the constants function (given above) in the Common.php file
Add the files (given above) key in your composer.json file
Run composer-dump to update autoload files
That's it. Use the file name and helper function name that describes your domian, so instead of constants you may use for example: site or your domain name as well.
You can create (or use an existing) a service provider and in the register method use the following code:
view()->share('constants', config('constants', []));
Using share on the view helper function will share the variable over all views.
You can now access this variable in any view, for instance with blade:
{{ array_get($constants, 'ip') }}

file_get_contents doesn't work in seed file but work in the routes file in laravel 5

I am trying to seed a table in laravel using a JSON output of the old table.
When I tried to file_get_contents('services.json') in the seed file, I get an exception that the file does not exist and also I tried using file_exists('services.json') and it returned false but when I tried it from the routes file, it works perfectly fine and my table seeds. My route looks like so:
Route::get('test', function(){
// return JWTAuth::parseToken()->getPayload()->get('username');
Illuminate\Database\Eloquent\Model::unguard();
// \Db::table('service')->truncate();
$servicesDataFromOldDB = file_get_contents('../database/seeds/services.json');
$servicesJson = json_decode($servicesDataFromOldDB);
$services = Illuminate\Support\Collection::make($servicesJson);
$services->each(function($service){
App\Service::create([
'id' => $service->id,
'name' => $service->title,
'description' => $service->desc,
'category' => $service->cat,
'type' => $service->type,
'hours' => $service->hours,
'price' => $service->price,
'note' => $service->note,
'devdays' => $service->devdays
]);
});
Illuminate\Database\Eloquent\Model::reguard();
});
I am fetching the same file from the same path and it is able to fetch it but not in the seed file. What am I missing?
EDIT
dd(file_exists(app_path() . '/database/seeds/services.json'));
Even this is returning false
And moreover I did a dd(__DIR__) in the seed file and it was the right path /var/www/html/archive/database/seeds
Using __DIR__ you can get the directory that the current file is in, then using realpath(), you can get the full, qualified path to the file.
realpath(__DIR__ . '../database/seeds/services.json');
This means that you can set the path relative to the directory of the file you're working in, and be sure that it will work from anywhere else in the code.

Laravel: Where to store global arrays data and constants?

I just started working with Laravel. I need to rewrite a whole system I made some years ago, using Laravel 4 as base framework. In my old system, I used to have a constant.php file with some constants declared, and a globals.php file which contained lots of array sets (for example, categories statuses, type of events, langs, etc.). By doing so, I could use something like
foreach ( $langs as $code => $domain ) {
// Some stuff
}
anywhere in my app.
My question is, how can I store that info in the so called "laravel way". I tried using some sort of object to store this info, setting this as a service and creating for it a facade:
app/libraries/Project/Constants.php
namespace PJ;
class Constants {
public static $langs = [
'es' => 'www.domain.es',
'en' => 'www.domain.us',
'uk' => 'www.domain.uk',
'br' => 'www.domain.br',
'it' => 'www.domain.it',
'de' => 'www.domain.de',
'fr' => 'www.domain.fr'
];
}
app/libraries/Project/ConstantsServiceProvider.php
namespace PJ;
use Illuminate\Support\ServiceProvider;
class ConstantsServiceProvider extends ServiceProvider {
public function register() {
$this->app->singleton('PJConstants', function() {
return new Constants;
});
}
}
app/libraries/Project/ConstantsFacade.php
namespace PJ;
use Illuminate\Support\Facades\Facade;
class ConstantsFacade extends Facade {
protected static function getFacadeAccessor() {
return 'PJConstants';
}
}
composer.json
"psr-4": {
"PJ\\": "app/libraries/Project"
},
and so I access that property as PJ\Constants::$langs.
This works, but I doubt it is the most efficient or correct way of doing it. I mean, is it the right way to "propagate" a variable by creating a whole Service Provider and facades and all such stuff? Or where should I put this data?
Thanks for any advice.
EDIT # 01
Data I want to pass to all controllers and views can be directly set in script, like in the example at the beginning of my post, but it can also be generated dynamically, from a database for example. This data could be a list of categories. I need them in all views to generate a navigation bar, but I also need them to define some routing patterns (like /category/subcategory/product), and also to parse some info in several controllers (Like get info from the category that holds X product).
My array is something like:
$categories = [
1 => ['name' => 'General', 'parent' => 0, 'description' => 'Lorem ipsum...'],
2 => ['name' => 'Nature', 'parent' => 0, 'description' => 'Lorem ipsum...'],
3 => ['name' => 'World', 'parent' => 0, 'description' => 'Lorem ipsum...'],
4 => ['name' => 'Animals', 'parent' => 2, 'description' => 'Lorem ipsum...']
]
Just as an example. Index is the id of the category, and the Value is info associated with the category.
I need this array, also, available in all Controllers and Views.
So, should I save it as a Config variable? How else could I store these data; what would be the best and semantically correct way?
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');
Note that the values you set will not persist. They are only available for the current request.
Update
The config is probably not the right place to store information generated from the database. You could just use an Eloquent Model like:
class Category extends Eloquent {
// db table 'categories' will be assumed
}
And query all categories
Category::all();
If the whole Model thing for some reason isn't working out you can start thinking about creating your own class and a facade. Or you could just create a class with all static variables and methods and then use it without the facade stuff.
For Constants
Create constants.php file in the config directory:-
define('YOUR_DEFINED_CONST', 'Your defined constant value!');
return [
'your-returned-const' => 'Your returned constant value!'
];
You can use them like:-
echo YOUR_DEFINED_CONST . '<br>';
echo config('constants.your-returned-const');
For Static Arrays
Create static_arrays.php file in the config directory:-
class StaticArray
{
public static $langs = [
'es' => 'www.domain.es',
'en' => 'www.domain.us',
'uk' => 'www.domain.uk',
'br' => 'www.domain.br',
'it' => 'www.domain.it',
'de' => 'www.domain.de',
'fr' => 'www.domain.fr'
];
}
You can use it like:-
echo StaticArray::$langs['en'];
Note: Laravel includes all config files automatically, so no need of manual include :)
Create common constants file in Laravel
app/constants.php
define('YOUR_CONSTANT_VAR', 'VALUE');
//EX
define('COLOR_TWO', 'red');
composer.json
add file location at autoload in composer.json
"autoload": {
"files": [
"app/constants.php"
]
}
Before this change can take effect, you must run the following command in Terminal to regenerate Laravel’s autoload files:
composer dump-autoload
For global constants in Laravel 5, I don't like calling Config for them. I define them in Route group like this:
// global contants for all requests
Route::group(['prefix' => ''], function() {
define('USER_ROLE_ADMIN','1');
define('USER_ROLE_ACCOUNT','2');
});
I think the best way is to use localization.
Create a new file messages.php in resources/lang/en (en because that is what is set in my config/app 'locale'=>'en')
return an array of all your values
return [
'welcome' => 'Welcome to our application'
];
to retrieve for laravel 5.3 and below
echo trans('messages.welcome');
or
echo Lang::get('messages.welcome');
for 5.4 use
echo __('messages.welcome')
laravel 5.0 localization
or
laravel 5.4 localization
Just to add to the above answer you will have to include the config class before you could start using it in Laravel 5.3
use Illuminate\Support\Facades\Config;
Atleast in Laravel 5.4, in your constructor you can create them;
public function __construct()
{
\Config::set('privileged', array('user1','user2');
\Config::set('SomeOtherConstant', 'my constant');
}
Then you can call them like this in your methods;
\Config::get('privileged');
Especially useful for static methods in the Model, etc...
Reference on Laracasts.com https://laracasts.com/discuss/channels/general-discussion/class-apphttpcontrollersconfig-not-found
Just put a file constants.php file into the config directory and define your constants in that file, that file will be auto loaded,
Tested in Laravel 6+
Create a constants class:
<?php
namespace App\Support;
class Constants {
/* UNITS */
public const UNIT_METRIC = 0;
public const UNIT_IMPERIAL = 1;
public const UNIT_DEFAULT = UNIT_METRIC;
}
Then use it in your model, controller, whatever:
<?php
namespace App\Models;
use App\Support\Constants;
class Model
{
public function units()
{
return Constants::UNIT_DEFAULT;
}
}

Zend Framework 2 custom style for each user

I am building an application for companies which sends anonymous-links to customers for filling out a questionnaire. The company should be able to change the colors and the logo of the questionnaire to reflect the affiliation to the company's CI.
My idea was to make a folder for every company (in my case, represented as doctrine entity Client) and load the layout's style.css and logo.png etc. dynamically from this folder.
The question: how do I implement this? How can I change a variable in the layout file from the controller? Or do I have to place the whole layout inside the view.phtml file for the ViewModel?
Thanks in advance!
If I had to have several layouts depending on some condition.
I would make the layouts for every company, set them in module.config.php
'view_manager' => array(
'template_path_stack' => array(
'module' => __DIR__ . '/../view/',
),
'template_map' => array(
'layout/company1' => __DIR__ . '/../view/layout/company1.phtml',
'layout/company2' => __DIR__ . '/../view/layout/company2.phtml',
)
),
Then in gloabal.php or in the same module.config.php would add some options:
'companies_layouts' => array(
'IDofComapny1' => 'layout/company1',
'IDofComapny2' => 'layout/company2',
)
And finally in the controller would do something like this:
public function indexAction()
{
$sm = $this->getServiceLocator();
// Getting company identifier
$companyId = $this->params()->fromRoute( 'companyId' );
// do something
...
$this->layout( $sm->get('Config')['companies_layouts'][$comanyId] );
return new ViewModel();
}
If you just need to set css depending on some conditions.
You can just do this in the view file:
switch( true ){
case some condition:
$css = 'file1.css';
break;
case some condition:
$css = 'file2.css';
break;
}
$this->headLink()->appendStylesheet( $css );
And in the layout file you should have next line:
<head>
...
<?= $this->headLink() ?>
...
</head>
You need to set style.css and logo file path according to company name in you action and then you can access this vairable in you layout also as same as you access in view file.
And set you css with headLink() function. and assign logo file in layout header.
You don't need to place layout code in view file.
Write below code on you controller. you can also access style variable in you layout.
return new ViewModel(array( 'style' => $style ,'logo' => $logo));

Append param to current URL with view helper in Zend

In my layout-script I wish to create a link, appending [?|&]lang=en to the current url, using the url view helper. So, I want this to happen:
http://localhost/user/edit/1 => http://localhost/user/edit/1?lang=en
http://localhost/index?page=2 => http://localhost/index?page=2&lang=en
I have tried the solution suggested Zend Framework: Append query strings to current page url, accessing the router directly, but that does work.
My layout-script contains:
English
If the default route is used, it will append /lang/en, but when another route is used, nothing is appended at all.
So, is there any way to do this with in Zend without me having to parse the url?
Edit
Sorry for my faulty explanation. No, I haven't made a custom router. I have just added other routes. My bad. One route that doesn't work is:
$Routes = array(
'user' => array(
'route' => 'admin/user/:mode/:id',
'defaults' => array('controller' => 'admin', 'action' => 'user', 'mode'=>'', 'id' => 0)
)
);
foreach( $Routes as $k=>$v ) {
$route = new Zend_Controller_Router_Route($v['route'], $v['defaults']);
$router->addRoute($k, $route);
}
Upd:
You must add wildcard to your route or define 'lang' parameter explicitly.
'admin/user/:mode/:id/*'
Additionally, according to your comment, you can do something like this:
class controllerplugin extends Zend_Controller_Plugin_Abstract
{
function routeShutdown($request)
{
if($request->getParam('lang', false) {
//store lang
Zend_Controller_Front::getInstance()->getRouter()->setGlobalParam('lang', NULL); //check if this will remove lang from wildcard parameters, have no working zf installation here to check.
}
}
}

Categories