Set Public Static in Vendor Folder - php

I want to set public static variable inside vendor folder.
I want to change this
public static $serverKey_as = 'my-secret-key';
into this, get the key from config -> app.php file
public static $serverKey_as = config('app.serverkey_as');
But i get this error
Symfony\Component\ErrorHandler\Error\FatalError: Constant expression contains invalid operations in file
this is my code in config -> app.php
'serverkey_as' => env('SERVERKEY_AS', 'my-defauly-secret-key'),
and this is my .env
SERVERKEY_AS = 'my-secret-key'
and this is what i've try but still no luck
<?php
namespace Midtrans;
class Config
{
public static $serverKey_as;
public function __construct()
{
return self::$serverKey_as = config('app.serverkey_as');
}
}
Got any hint for me?

First of all: you really shouldn't change code in the /vendor directory. That directory contains code made and maintained by other people.
Furthermore, an initial static variable assignment cannot contain function calls of any kind. I would suggest using the boot() method in your AppServiceProvider to change the static variable to the value you want:
public function boot()
{
\Midtrans\Config::$serverKey_as = config('app.serverkey_as');
//...
}

Related

How to make a class accessible globally in a Laravel application?

I am trying to create a global helper to store site settings in my Laravel application. Meaning, I need a helper to set settings from a controller and access that settings object from anywhere using the same helper. I don't need to store these settings on a database or in files. That's why I need these kinds of functionality.
What is did are as follows,
Create a class in app/Helpers directory called SettingsHelper and auto load the directory.
namespace App\Helpers;
class SettingsHelper{
protected $vars;
public function all(){
return $this->vars;
}
public function get($key, $default = null){
if (is_array($this->vars) && array_key_exists($key, $this->vars)) {
return $this->vars[$key];
}
return $default;
}
public function put($key, $value){
return $this->vars[$key] =$value;
}
}
Create a helper function to resolve the class if not already resolved
if ( ! function_exists('settings')) {
function settings(){
if (app('\App\Helpers\SettingsHelper')) {
return app('\App\Helpers\SettingsHelper');
}
return app()->make('\App\Helpers\SettingsHelper');
}
}
Set and get setting using the helper
settings()->put('test', 'test2');
dd(settings()->all());
But null is returned. I tried dumping settings()->put('test', 'test2') and it returned the passed value test2.
Is this the correct approach for this?
You should register your class as a singleton in the application container before you can use it. Otherwise, the app() function will create a new instance on every use. You can also give the instance a name in the container, this way, you don't have to create your own global function.
In your AppServiceProvider.php:
$this->app->singleton('settings', function ($app) {
return new \App\Helpers\SettingsHelper;
});
And now you can use your class with:
app('settings')->put('test', 'test2');
dd(app('settings')->all());
Create a service provider php artisan make:provider HelperServiceProvider
Then in the register method do something like:
public function register()
{
foreach (glob(app_path().'/Helpers/*.php') as $filename) {
require_once($filename);
}
}
Make a singleton in a provider, example AppServiceProvider.php.
use App\Helpers\SettingsHelper;
$this->app->singleton(SettingsHelper::class, function ($app) {
return new SettingsHelper($vars); // create your class with the vars you need
});
Everywhere in your app there can only be 1 settings helper and you can get it like so.
use App\Helpers\SettingsHelper;
app(SettingsHelper::class);

How to access static variable declared in Controller from Library in Codeigniter?

I want to access the static variable declared in Codeigniter Controller and I want to use it in the Library. Here is the code.
Controller Location & Name:
Name : Console
Location : ./application/controllers/Console.php
Library Location & Name:
Name : Api
Location : ./applications/libraries/Api.php
Console.php
class Console extends CI_Controller {
public static $access_agents = [
'2017_app_v1.0',
'2017_api_v1.0'
];
public static $developer_secret = [
'HTTP_X_DEVELOPER_SECRET' => 'XYZ'
];
}
Api.php
class Api
{
public static $CI;
public function __construct()
{
self::$CI = & get_instance();
}
public static function print_services_list($list)
{
if(self::get_custom_header(##### CALL_STATIC_VARIABLE_HERE ######))
$array = [
'status' => '200',
'message' => 'OK',
'text' => "List of APIs under this Interface gateway.",
'data' => $list
];
self::print_json_array($array);
}
}
As I described I want to access the Static variable declared in Console Class into here where I have used ##### CALL_STATIC_VARIABLE_HERE ######
I have tried things like these: (I knew it wouldn't work probably and I was right)
Console::$developer_secret - NOT WORKING
self::$CI->Console::$developer_secret - NOT WORKING
self::$CI->Console->$developer_secret - NOT WORKING
Why don't you place these variables in the config file?
Create a PHP file in application/config folder. Name it whatever you want. Then place your variables in the file as below.
<?php
$config['static_var']['your-static-variable-name'] = 'Whatever value you want to initialize'
If you want to add another variable
<?php
$config['static_var']['your-another-static-variable-name'] = 'Whatever value you want to initialize'
Once the file is saved please load the config file in your library.
class Api
{
protected $CI;
protected $my_var;
protected $my_another_var;
public function __construct()
{
$this->CI =& get_instance();
$this->CI->load->config('your config file name');
$this->my_var = $this->CI->config->item('your-static-variable-name','static_var');
$this->my_another_var = $this->CI->config->item('your-another-static-variable-name','static_var');
}
}
Now use $myvar wherever you want. Hope this can help you.

Laravel - Unable to override the create method for a model

When overriding the base Laravel model create method, the application fails. No errors are sent back to the browser, and the server logs are empty. The strange thing, it works just fine without the override. Not sure what I'm doing wrong.
Simplified controller function:
public function save(Request $request, $id = 0) {
$myModel = MyModel::find($id);
$data = $request->all();
if (!$myModel) // Create a new row
{
$myModel = MyModel::create($data);
}
// ...
}
This works fine until I add this function to the model:
class MyModel extends Model
{
// ...
public static function create($attributes = [])
{
return parent::create($attributes);
}
// ...
}
Just to clarify, I'm not looking for a different way to implement this. I just need to know why the parent call is failing for me.
Here's some server info...
Server OS: Windows 7 (personal PC with XAMPP)
Laravel version 5.4.15
PHP version 5.6.30
The explanation is that the public static function create() is not defined in the Illuminate\Database\Eloquent\Model class.
Is handled as dynamic method call, that is is handled by calling the function:
public static function __callStatic($method, $parameters)
In the Illuminate\Database\Eloquent\Model class.
At the end the create() function is defined in the Illuminate\Database\Query\Builder class.
That is the reason you cant override it in your Model and call parent::create()
IMHO I have not tested entirely, you could try with:
public static function create($attributes)
{
return (new static)->newQuery()->create($attributes);
}
About errors, you should make sure you have enabled log_errors on your server. About the error, when you extend class and want to override method, it should have same signature, so it should be:
public static function create(array $attributes = [])
{
// Your custom code goes here
return parent::create($attributes);
}
(notice array type hinting). Obviously I assume you are going to add something more in this function :)

Changing widget assets path at runtime

I have a widget that uses assets. The asset look like this:
class publicHeaderNavbarAsset extends AssetBundle {
public $sourcePath = '#app/components/#device';
public $css = [
'styles.css'
];
public $js = [];
public $depends = [];
}
I also have a (bootstrapped) component, defined like that:
class Aliases extends Component {
public function init() {
Yii::setAlias('#device', Utils::device());
}
}
Utils::device() is a function that parses the UA of the device and returns mobile, tablet or desktop, depending on the device type.
The problem is that Yii2 doesn't seem to be converting #device to the value it has. I first thought that it could be my fault, but then I changed the sourcePath to:
public $sourcePath = '#app/components/#app';
just to see if that will trigger an error with a duplicated path (basepath/componenets/basepath), but it didn't.
Is there a way I can change the sourcePath of my asset at runtime? Or maybe make Yii2 parse all the aliases in sourcePath?
Look at the getAlias function http://www.getyii.com/doc-2.0/api/yii-baseyii.html#getAlias()-detail
It will basically not match your second alias in the string you have given it.
You can try setting
Yii::setAlias('#device', '#app/components/' . Utils::device());
and
public $sourcePath = '#device';
This should work as you should be able to set an alias based on another alias
http://www.yiiframework.com/doc-2.0/guide-concept-aliases.html#defining-aliases

Invalid argument supplied for foreach() yii-app-basic

I've one module -> users.
->modules
->users
->controllers
->models
->views
->Users.php
I created one 'config.php' inside 'config' folder of 'users' modules.
->modules
->users
->config
->config.php
->controllers
-> List of Controllers
->models
-> List of models
->views
-> List of Views
->Users.php
And, i gave directory path of config.php in init() method of Users.php, as
modules/users/Users.php
<?php
namespace app\modules\users;
class Users extends \yii\base\Module
{
public $controllerNamespace = 'app\modules\users\controllers';
public $commonModel = 'app\modules\users\models\Users';
public function init()
{
parent::init();
\Yii::configure($this,require(__DIR__.'/config/config.php'));
}
}
But, it is giving error like
PHP Warning – yii\base\ErrorException
"Invalid argument supplied for
foreach()".
Screenshot
I am taking reference from Yii2.0 Guide to include a path inside init() method.
Please help me to rectify this issue.
Thanks.
From what I can see, you're passing in the PHP code to your config file, instead of passing in a configuration array
Instead of this...
\Yii::configure($this, require(__DIR__.'/config/config.php'));
Try doing this...
$config = require(__DIR__.'/config/config.php');
\Yii::configure($this, $config);
In your config.php file you should be returning an array, if you're using the basic-app config file and adding to that then it should be set up like this already
The problem comes from the configuration file. The configureation file must returns an array. Make sure that the config file is as follows:
<?php
$config = [
'name1' => 'value1',
'name2' => [/* something here */],
];
return $config;
you edit file model and delete code:
/**
* #inheritdoc
* #return DriverSearch the active query used by this AR class.
*/
public static function find()
{
return new DriverSearch(get_called_class());
}

Categories