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

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.

Related

codeIgniter can't access session in Hook

I have created on hook to set current visiting URL to session. I have to use this URL later on. I have called session method of codeIgniter using $this->CI =& get_instance(); and then $this->CI->session->userdata but it is giving
Trying to get property of non-object on $this->CI->session->userdata line
I have done following things to enable hooks in CI
config.php
$config['enable_hooks'] = TRUE;
hooks.php
$hook['pre_controller'] = array(
'class' => 'Preclass',
'function' => 'checkreq',
'filename' => 'preclass.php',
'filepath' => 'hooks',
'params' => array()
);
preclass.php
class Preclass
{
private $CI;
public function __construct()
{
$this->CI =& get_instance();
}
public function checkreq($value='')
{
var_dump($this->CI->session->userdata);
die;
}
}
Note: Don't close this post as Duplicate of PHP errors. As I know about errors. This is in CodeIgniter and I want to check session before any controller method gets invoked.
From comment: "But I want it before controller methods invoke even before constructor"
To solve your issue, this is about the best you can do:
Make an MY_Controller.php in application/core:
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
// class is just an alias for the controller name
if (!$this->user->is_allowed($this->router->class)) {
redirect('somepage');
}
}
}
Then have all your controllers extend MY_Controller:
class Somecontroller extends MY_Controller {
public function __construct() {
parent::__construct();
// nothing below the above line will be reached
// if the user isn't allowed
}
}
Whether or not you have a __construct() method in the class: nothing will happen so long as the user isn't allowed to access the page e.g. nothing after parent::__construct() will be called - even methods. Again, the fact that the parent constructor is called is implied if no constructor exists for the controller.
Note: if you autoload a model and do the same logic in the MY_Controller in the models __construct() the same results should be achieved. I just find this method cleaner.
This is not possible in Codeigniter as session itself a library and you are trying to call it pre_controller. When controllers not loaded yet how can you use it even in hook.
Solution
You may use post_controller_constructor instead what are using now
$hook['post_controller_constructor'] = array(
'class' => 'Preclass',
'function' => 'checkreq',
'filename' => 'preclass.php',
'filepath' => 'hooks',
'params' => array()
);
otherwise you may also use native session here
hope it help

Zend Framework 3 How Access Globle.php file

In Zend Framework 3 i Have create on file in Config/autoload/myconfig.globle.php
return [
"myvariable" => [
"key" => "value"
]
];
i have access through this
$config = $this->getServiceLocator()->get('Config');
give following error:
A plugin by the name "getServiceLocator" was not found in the plugin manager Zend\Mvc\Controller\PluginManager
so now how can i access this file in Controller in Zend Framework 3.
Many things here:
First of all, the service locator has been removed. Therefore, you have to create a factory for your controller, or use a configuration based abstract factory.
Then, your files must respect the pattern defined in application.config.php, which means global.php, *.global.php, local.php or *.local.php. In your message your config is named myconfig.globle.php instead of myconfig.global.php.
So then:
final class MyController extends AbstractActionController
{
private $variable;
public function __construct(string $variable)
{
$this->variable = $variable;
}
public function indexAction()
{
// do whatever with variable
}
}
Also you need a config:
return [
'controllers' => [
'factories' => [
MyController::class => MyControllerFactory::class,
],
],
];
Finally, let's make that MyControllerFactory class:
final class MyControllerFactory
{
public function __invoke(Container $container) : MyController
{
$config = $container->get('config');
if (!isset($config['myvariable']['key']) || !is_string($config['myvariable']['key'])) {
throw new Exception(); // Use a specific exception here.
}
$variable = $config['myvariable']['key']; // 'value'
return new MyController($variable);
}
}
That should be about it :)

Empty route leeds to 404-Error - SilverStripe 3.5

Like superficial descriped in SilverStripe Docs, I'm trying to set a custom controller for my homepage.
I changed the default homepage link to 'custom-home' and added those two routes.
The second one, with the path in it works and directs me to my controller. The first (empty) one just sends me to an 404-error page.
Couldn't figure out how to fix that. Any suggestions?
routes.yml
Director:
rules:
'': 'MyHome_Controller'
'custom-home': 'MyHome_Controller
_config.php
RootURLController::set_default_homepage_link('custom-home');
MyHome_Controller.php
<?php
class MyHome_Controller extends Page_Controller {
private static $allowed_actions = [];
private static $url_handlers = [];
public function init() {
parent::init();
}
public function Link($action = null) {
return Director::baseURL() . 'custom-home';
}
public function index() {
$data = [
'Title' => 'Hello World',
'ClassName' => __CLASS__,
];
return $this
->customise($data)
->renderWith([__CLASS__, 'Page']);
}
}
I believe the way the empty route (RootURLController) works is that you're telling it the URLSegment of a page in the CMS that should resolve to the root URL. So I think what you need to do is go into the CMS and change the URLSegment of your CustomHomePage to 'custom-home'.

CodeIgniter Hooks to display content on all pages

I have a sidebar displayed on all my websites pages the same content should be displayed each time:
current cash
username
more info...
For the username I'm using the session within the regular controllers so that's alright but for the cash, I need to make a call to the database. I've tried to use hooks but I can't figure out how to display the info in the view (the variable is undefined).
I'm stuck when loading the session.
I get the message: Unable to locate the specified class: Session.php eventhough my session library is autoloaded and I added it one more time in the hook, just in case...
autoload.php
$autoload['libraries'] = array('database','session','form_validation','pagination', 'template');
My hooks.php
$hook['post_controller_constructor'] = array(
'class' => 'get_info_general',
'function' => 'get_info_general',
'filename' => 'get_info_general.php',
'filepath' => 'hooks',
'params' => ''
);
My get_info_general.php
class get_info_general extends CI_Controller{
private $CI;
public function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->library('session');
$this->load->library('database');
}
function get_info_general(){
$this->load->model('usersModel');
$cash = $this->usersModel->check_cash_player();
$data['cash'] = $cash;
} }
In UsersModel:
public function check_cash_player(){
$currentUserID = $this->usersModel->get_user_id();
$query = $this->db
->select('cash')
->from('place')
->where('id_player', $currentUserID)
->get();
return $query->row('cash');
}
UPDATE:
After #alexander popov suggestion I changed the code to:
class get_info_general {
private $CI;
public function __construct() {
$CI =& get_instance();
$CI->load->helper('url');
$CI->load->library('session');
}
function get_info_general(){
$this->load->model('usersModel');
$cash = $this->usersModel->check_cash_player();
$data['cash'] = $cash;
} }
And I get: Undefined property: get_info_general::$load
UPDATE 2:
Using the code provided here I don't get any error message and my page is displayed. However $cash is still undefined in my page. Adding the following code to get_info_general.php doesn't help:
$data['cash'] = $cash;
$data['main_content'] = 'loginForm';
$this->load->view('templates/default',$data);

codeigniter callback from private methods not working

I doing form validation in CodeIgniter using Form Validation Library and my custom callbacks.
public function insert_user()
{
if($this->input->post('submit')) {
// load form validation library
$this->load->library('form_validation');
// configurations
$config = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required|callback_username_check'
)
);
$this->form_validation->set_rules($config);
// .... continue ....
}
}
When method is public, it is working as expected.
public function username_check($username)
{
// do some stuffs here
}
When I make method as private, it is not working.
private function username_check($username)
{
// do some stuffs here
}
Why callbacks from private methods are not working?
Why I need this?
Public methods in CodeIgniter controllers are accessible by URLs like an example above
http://example.com/controller_name/username_check/blabla
I don't want callback methods accessible publicly.
The callback function must be public. Codeigniter Form validation class access your function at current controller so it may not be private..
To go around your problem you may think about extending you CI_Form_validation class with a My_form_validation..
class MY_Form_validation extends CI_Form_validation
{
public function __construct()
{
parent::__construct();
}
function username_check($str)
{
/* your code */
}
}
Then in your validation you must set only..
'rules' => 'required|username_check'
Private function can only be accessed by an object of the class. This function are visible in its own class only. Read more about variable/function scope here

Categories