CodeIgniter use a global session variable from contructor - php

I need to use a session information in various functions of my controller, but I can't initialize it in the constructor, because I get an error. Message: Undefined property: Soporte::$session
class Soporte extends MY_Controller {
function __construct(){
parent::__construct( $module, $functionality );
}
public function actualizarSolicitud( $id_solicitud ){
$session_data = $this->session->userdata('session_user');
$user = $session_data['usuario'];
...
}
public function adminHistorico(){
$session_data = $this->session->userdata('session_user');
$user = $session_data['usuario'];
$config = array();
...
}
...
}
There's a way to initialize a global variable $user?

Try like below, model is quite complicated so I'm not providing it's code, but you should get the point. Any questions let me know.
/**
* This class is used for performing all read/write session operations
* Native php session is utilized (MY_Session library)
*/
class SessionManager extends BaseLibrary {
private $oUser;
public function __construct() {
parent::__construct();
$this->CI->load->model('User');
}
public function setUser(User $oUser) {
$this->CI->session->set_userdata('userId', $oUser->getId());
}
public function getUser() {
if ($this->oUser === null) {
$this->oUser = new User();
if ($this->CI->session->userdata('userId')) {
$this->oUser->setId($this->CI->session->userdata('userId'));
}
}
return $this->oUser;
}
public function logout() {
$this->CI->session->set_userdata('userId', NULL);
}
}

Related

Laravel Controller use same object in two functions

Is there a way to use a object variable instantiated from a class in two functions?
Here's the code I've tried, but its just returning null:
class bookAppointmentsController extends APIController
{
private $business;
public funcition check($key)
{
$this->business = new APIClass();
$setconnection = $this->business->connectAPI($key);
}
public function book()
{
dd($this->business) //returns null
$this->business->book();
}
}
I am trying to use the $business object in two functions but it does not work, when I dd($business) it returns null
Any way to do this?
Move the instantiation to the constructor:
public function __construct(APIClass $business)
{
$this->business = $business;
}
However, it would be better if you make Laravel do the heavy lifting and prepare the APIClass for you.
In your AppServicePorvider under the register method, you can create the APIClass
/**
* Register any application services.
*
* #return void
*/
public function register()
{
$this->app->bind('APIClass', function ($app) {
$api = new APIClass();
// Do any logic required to prepare and check the api
$key = config('API_KEY');
$api->connectAPI($key);
return $api;
});
}
Check the documentations for more details.
Maybe the solution could be to make the variable Global
You could make the variable global:
function method( $args ) {
global $newVar;
$newVar = "Something";
}
function second_method() {
global $newVar;
echo $newVar;
}
Or you could return it from the first method and use it in the second method
public function check($key)
{
$this->business = new APIClass();
$setconnection = $this->business->connectAPI($key);
return $this->business;
}
public function book()
{
$business = check($key);
$business->book();
}

How to access a variable with random value inside a class?

class Session{
protected $git = md5(rand(1,6));
public function __construct($config = array())
{
//// some code
$ses_id = $this->git;
}
public function _start_session()
{
//code again..
}
}
Here I can't assign a random value like this to variable called git. How can I do this if it is possible?
That random value need to be first time generated value only till the time it converts to Null.
Perform random inside your constructor,
class Session{
protected $git;
public function __construct($config = array())
{
//// some code
$this->git = md5(rand(1,6));
$ses_id = $this->git;
}
public function _start_session()
{
//code again..
}
}
Try setting the value of your variable in your constructor.
constructor will run every time you create an instance of your class.
try this code:
class Session{
protected $git;
public function __construct($config = array())
{
//// some code
$this->git = md5(rand(1,6));
}
public function _start_session()
{
//code again..
}
}
:)
Declare a variable inside a class,initialize the variables in class inside a constructor, which sets the variables once the object for that class is declared anywhere in the code.
I updated this answer if you want to do not change your session variable on each constructor call then use the below procedure.
class Session{
protected $git;
public function __construct($config = array())
{
$this->git = md5(rand(1,6));
if(!isset($_SESSION['ses_id']))
{
$_SESSION['ses_id'] = $this->git;
}
}
public function _start_session()
{
//code again..
}
}
I hope this helps you.
Try this using a global variable to track the random number:
class Session{
protected $git;
public function __construct($config = array())
{
//// some code
if (!isset($GLOBALS['random_val'])) {
$GLOBALS['random_val'] = md5(rand(1,6));
}
$this->git = $GLOBALS['random_val'];
$ses_id = $this->git;
var_dump("Session ID: ".$ses_id);
}
public function _start_session()
{
//code again..
}
}
$ses1 = new Session(); // Outputs string(44) "Session ID: 1679091c5a880faf6fb5e6087eb1b2dc"
$ses2 = new Session(); // Outputs string(44) "Session ID: 1679091c5a880faf6fb5e6087eb1b2dc"

how to use objects created within the parent class in the child class PHP

I have this code and i´m trying to use a object
<?php
class Controller {
public $_view;
public function __construct() {
$this->_view = new View();
return $this->_view;
}
}
class View {
public $_params = array ();
public function set_params($index_name,$valores) {
$this->_params[$index_name] = $valores;
}
public function get_param($index_name){
return $this->_params[$index_name];
}
}
?>
i would like to do this:
class Index extends Controller {
public function index() {
$model = Model::get_estancia();
$usuarios = $model->query("SELECT * FROM usuarios");
$this->_view->set_params(); // cant be used.
$this->load_view("index/index");
}
}
i would like to use the set_parms function.
but i can't see the View Function, then i can not use.
Can someone explain and advise me a good and safe way?
Correction from Phil: If a __construct() method isn't found, PHP will revert to legacy constructor syntax and check for a method with the same name as the object. In your case the method index() is being treated as the constructor, and is preventing the parent's constructor from loading the view object into the $_view property.
You can force a class to inherit a parent's constructor by defining __construct() in the child and calling the parent's constructor:
public function __construct() {
parent::_construct();
}
Here is the fixed code:
<?php
class Controller {
public $_view;
public function __construct() {
$this->_view = new View();
return $this->_view;
}
}
.
class View {
public $_params = array ();
public function set_params($index_name,$valores) {
$this->_params[$index_name] = $valores;
}
public function get_param($index_name){
return $this->_params[$index_name];
}
}
.
class Index extends Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$model = Model::get_estancia();
$usuarios = $model->query("SELECT * FROM usuarios");
$this->_view->set_params(); // cant be used.
$this->load_view("index/index");
}
}

php new class object not being instanced

I am trying to create a new model object from my mvc controller but the page doesn't generate. Is there any reason why I can't do this? Surely I should be able to create an object inside an existing one?
Sorry to be so simplistic, and I know I sound like an idiot, but I'm not sure how to explain what I am doing wrong.
class controller_landing extends controller_base
{
public function __construct($get,$post)
{
parent::__construct($get,$post);
$this->model = new model_landing; <-----problem line here
}
}
abstract class controller_base
{
//store headers
protected $get;
protected $post;
//store layers
protected $view;
protected $model;
protected function __construct($get,$post)
{
//store the header arrays
$this->get = $get;
$this->post = $post;
//preset the view layer as an array
$this->view = array();
}
public function __destruct()
{
//extract variables from the view layer
extract($this->view);
//render the view to the user
require_once('view/'.$this->get['controller'].'_view.php');
}
}
class model_landing extends class_mysqli
{
public function __construct
{
echo "landing model";
}
}
class class_mysqli
{
public function __construct
{
echo "mysqli";
}
}
I don´t know, but I think you are missing brackets.
There
public function __construct
{
echo "landing model";
}
should be
public function __construct()
{
echo "landing model";
}

Class function only available to "parent" - PHP

I want to create a function in a class that is available for a set of users, but that they won't be able to access. Ex:
class Stuff_for_user {
private $errors;
/*
* private $errors gets modified by private functions
*/
public function get_errors(){ // This is for users to display errors.
return $this->errors;
}
/*something here...*/ function set_errors($str){
$this->errors = $str;
}
}
So far so good, but now I want the parent class to be able to set Stuff_for_User's errors:
class Main_mess {
public index(){
$user_available_data = new Stuff_for_user();
if($big_error)
$user_available_data->set_errors("BIG ERROR!!!");
$this->send_to_users($user_available_data);
}
}
I want only Main_mess to be able to access Stuff_for_User's set_errors() method. Is that possible?
No, that is not possible like that, since Main_mess is not a parent class of Stuff_for_users (and this is probably what you want, looking at what your code actually does). So set_errors has to be public if you want to call it from the outside.
This is not possible how you want to implement it.
Some ideas (i dont know why or how you want to do that but just ideas...):
do set_error($str,$access_key) and let $access_key be an access string only you know!
let Stuff_for_user be in Extended_Stuff_for_user which has the set_error function like:
class Extended_Stuff_for_user {
private $errors;
private $Stuff_for_user;
public function set_errors() {
/* ... */
}
public function getStuffForUser() {
return $this->Stuff_for_user;
}
}
It seems that you are looking for implementation of something called friend class in php. Well .. i'm sorry to tell you this, but it is not possible.
You should look at other possible solutions to your problem.
class SecureContainer{
protected $user = null;
protected $target = null;
public function __construct( $target, $user )
{
$this->target = $target;
$this->user = $user;
}
public function __call( $method, $arguments )
{
if ( $this->user->isAllowed(getType( $this->target ), $method))
{
return call_user_func_array(
array( $this->target, $method), $arguments );
}
}
}
Use it like this:
$something = new UnsecureSomething;
$user = new User( $uid );
$something = new SecureContainer( $something, $user );
This should let you control the access to methods.
Yes it possible but it can be dirty.
Like This.
class Stuff_for_user {
private $errors;
/*
* private $errors gets modified by private functions
*/
public function get_errors(){ // This is for users to display errors.
return $this->errors;
}
/*
This way the child classes of Main will able be to use the set_errors function;
*/
function set_errors($class,$str){
if($class instanceof Main_mess)
{
$this->errors = $str;
}
/*
AndThis way the only Main_mess will be able;
*/
function set_errors($class,$str){
if(get_class($class)=="Main_mess")
{
$this->errors = $str;
}
}
class Main_mess {
public index(){
$user_available_data = new Stuff_for_user();
if($big_error)
$user_available_data->set_errors($this,"BIG ERROR!!!");
$this->send_to_users($user_available_data);
}
}

Categories