Why Session details are not accessible inside php namespace - php

I have developing a basic session handler class. The issue is when ever I am setting session into any controller action, same session details are not accessible in other action/controller. It displays me empty array. Entire system is php namespace oriented.
Reference: Session Manager
We do save and retrieve session as below.
use Cygnite\Common\SessionManager\Session;
use Cygnite\Common\Encrypt;
$session = new Session(new Encrypt);
$session->save($key, $value);
$userDetails = $session->get($key);
var_dump($userDetails);
It works inside the same action and but when ever I am redirecting into some other controller ->action session doesn't display anything.
Can anyone help?

Probably you create in each controller new Session object. And it's quite possible you should create one Session object and inject it for example as constructor argument to other classes.
use Cygnite\Common\SessionManager\Session;
use Cygnite\Common\Encrypt;
$session = new Session(new Encrypt);
$session->save('something', 'My data');
class A
{
private $session;
public function __construct($session) {
$this->session = $session;
echo $this->sesssion->get('something'); // it should work
$x = new Session(new Encrypt);
echo $x->get('something'); // possible it won't work
}

Related

Magento data array storage in custom session object

I am using my own session class, in that class, I am using some protected data members and some public data methods While I storing some variable on my session class Like
Mage::getSingleton('decision/session')->storeProductInfo('2');
Here is function implementation, $this->_productId is the private data member of my session class.
Public function storeProductInfo($product_id){
$this->_productId = $product_id;
return $this;
}
I am getting the stored variable by calling the below statement, it return me "null".
$product_stored_id = Mage::getSingleton('decision/session')->getStoredProductInfo();
public function getStoredProductInfo(){
return $this->_productId;
}
Even
Mage:getSingleton('decision/session')->setData('product_id', '2');
Didn't working. Can you please let me know where I am going wrong? I have to store some arrays in my session that's why I created my own session class to separately deal with my logic.
Use Magento Magic Method get and set
For that when your observer will call then you can create the session and set the value of that.
you can set the session using set, getting value using get and unset session using uns.
Mage::getSingleton('core/session')->setMySessionVariable('MyValue');
$myValue = Mage::getSingleton('core/session')->getMySessionVariable();
echo $myValue;
To Unset the session
Mage::getSingleton('core/session')->unsMySessionVariable();
$inputMessage = 'Hello World';
Mage::getSingleton('core/session')->setWelcomeMessage($inputMessage);
Now you want to echo the "welcome message" somewhere else in your code/site.
$outputMessage = Mage::getSingleton('core/session')->getWelcomeMessage();
echo $this->__($outputMessage);

How to save an object in PHP and access it everywhere?

I am new to PHP and I want to save an object from this class which I can access in my webservice this object hold a sessions id which can be used for calling an API:
MyObject.php:
class MyObject {
private $sessionId = '';
private function __construct(){
$this->sessionId = '';
}
public static function getInstance() {
if (!$GLOBALS['MyObject']) {
echo 'creating new instance';
$GLOBALS['MyObject'] = new MyObject();
}
return $GLOBALS['MyObject'];
}
public function getSessionsId() {
if ($GLOBALS['MyObject']->sessionId == '') {
// Do curl to get key (works)
if (!curl_errno($curlCall)) {
$jsonObj = json_decode($result);
$sessionID = $jsonObj->session_id;
$GLOBALS['MyObject']->sessionId = $sessionID;
}
}
return $GLOBALS['MyObject']->sessionId;
}
}
Webservice GetKey.php
include 'MyObject.php';
$instance = MyObject::getInstance();
echo $instance->getSessionsId();
The I visit the GetKey.php file it always echoes 'creating new instance'
what you store in $GLOBALS will be destroyed when the page is loaded... that variable is available only when the response is being created...
You don't save an object and use it everywhere (for all users) .. you are in php :) and you can store it anywhere... but if you're in a function then it will be destroyed when you are outside the function...
And in webservices you don't use session because it won't exist at next operation call
In the case that you want to store that variable for multiple requests of the same user you can store it in $_SESSION and not in $GLOBALS...
In PHP everything is destroyed when the user gets the response... (only session is an exception)... a session is like in java or any other language... you have it / user and you can modify it at request time... you don't have something like applicationScope and store there everything for all users... everything is being recreated at every request

Setting Sessions inside PHP Class

I'm creating a user class to handle my logins. As I wish to set the sessions inside the class after the username and password are validated, do I have to use session_start() at the top of the class, inside the public function where the sessions are to be set, or where the instance is created? Perhaps it could go inside function _construct()?
This is how I would like to call the class:
<php
include('user_class.php');
$user = new user;
$user->login($username,$password);
?>
You can just add session_start(); at the top of the file you're including the class in.
So
<?php
session_start();
include('user_class.php');
$user = new user;
$user->login($username,$password);
?>
would work.
Next to your user-class create yourself a session-class as well.
The user-class then is just storing itself into the session class and does not need to take care about calling session_start or not, that's the job of the session-class.
<php
include('session_class.php');
include('user_class.php');
$session = new session;
if ($session->hasRegisteredUser()) {
$user = $session->getRegisteredUser();
} else {
$user = new user;
    $user->login($username, $password);
$session->setRegisteredUser($user);
}
Does this answer your question or do you need now to know how to do it with the session class?
Yes you can use sessions inside your classes because sessions are global variables in php.
Code Example(adding a new session variable):
<?php
class sessionControle{
...
...
public function addSession($index, $value){
$_SESSION[$index] = $value;
return $_SESSION[$index];
}
}
?>
in your main php file you can include the function $_SESSIONS are global
Code in your main file:
<?php
session_start();
include_once("myClass.php");
$Se = new sessionControle;
echo $Se->addSession('User', 'Crx');
//Double check here !!
echo $_SESSION['User'];
?>
Output: Crx

Accessibility of a session in a view

I have created a Zend session in a view:
$user = Tools::getUserByLoginAndPassword($form);
if ($user instanceof Membre)
{
$sessionUser = new Zend_Session_Namespace('user');
$sessionUser->data = $user;
$this->_redirect('/adresse');
}
I have tested $sessionUser->data, it contains the right data.
But i need to get this session in another view, and there, it's not working anymore...
for instance
<?php var_dump($sessionUser->data->prenom); ?>
displays "NULL"
it worked fine in the previous view but not in this one.
I have placed my Zend_Session::start();
in the init() function of my controller...
thanks in advance for your help
If you want to use your session in another view, you have to instantiate it again. So if you use the following code you should be able to access your data:
<?php
$session = new Zend_Session_Namespace('user');
Zend_Debug::dump($session->data);
?>

How to use Zend\Session in zf2?

Does anybody try zf2? I can not understand new mechanism of using sessions in zf2. How can I write and read to/from the session in new zend framework?
Also I can not find any examples in the internet.
Some examples of zf2 sessions usage:
Session creation:
use Zend\Session\Container;
$session = new Container('base');
Check that key exists in session:
$session->offsetExists('email')
Getting value from the session by key:
$email = $session->offsetGet('email');
Setting value in session:
$session->offsetSet('email', $email);
Unsetting value in session:
$session->offsetUnset('email');
And other easy way to use session are:
$session = new Container('foo');
// these are all equivalent means to the same end
$session['bar'] = 'foobar';
$session->bar = 'foobar';
$session->offsetSet('bar', 'foobar');
Definitely yes, you should use Zend\Session\Container
Container extends of ArrayObject and instantiates with ARRAY_AS_PROPS flag that means you can easily iterate through properties and read/write them, e.g.
use Zend\Session\Container as SessionContainer;
$this->session = new SessionContainer('post_supply');
$this->session->ex = true;
var_dump($this->session->ex);
First argument is session namespace and second — Manager. Manager is a facade for Storage and SaveHandler and it's configured with ConfigInterface in order to save your session data in DB or Memcache server.
I'm currently working with zf2. I found usage of Sessions in:
Zend\Authentication\Storage\Session.php
Maybe you can find your answer there.
If you are trying to use session in your login action, you can use: "Zend\Authentication\AuthenticationService". It Authenticates the user and store session as well.
getStorage()->write($contents) will store the session.
well here is the brief example. i have implemented regarding maintaining session on successful authentication of user.
<?php
$registry = Zend_Registry::getInstance();
$DB = $registry['DB'];
$authAdapter = new Zend_Auth_Adapter_DbTable($DB);
$authAdapter->setTableName('user');
$authAdapter->setIdentityColumn("user_name");
$authAdapter->setCredentialColumn("user_password");
//get values
$username = $request->getParam('username');
$password = $request->getParam('password');
//set values
$authAdapter->setIdentity($username);
$authAdapter->setCredential($password);
$auth = Zend_Auth::getInstance();
//to store in session
$auth->setStorage(new Zend_Auth_Storage_Session('front'));
$authResult = $auth->authenticate($authAdapter);
if ($authResult->isValid()) {
$authAdap = $authAdapter->getResultRowObject(null, "Password");
$auth->getStorage()->write($authAdap);
$this->_redirect('/login/controlpannel');
} else {
$this->_redirect('/login/login');
}
?>
getting values or check data stored in session related to user
<?php
$auth = Zend_Auth::getInstance();
$auth->setStorage(new Zend_Auth_Storage_Session('front'));
if($auth->hasIdentity()){
$data = $auth->getStorage()->read();
print_r($data);
}else{
$this->_redirect('/login/login');
}
?>
hope this could help someone
use Zend\Session\Container;
public function createAction(){
$session = new Container('name');
$session->offsetSet('session_variable', $value);
}
//the above codes are used for create session.
public function take_valuesAction(){
$session = new Container('name');
echo $value = $session->offsetGet('session_variable');
}
//the above codes are used for take values from session.
public function destroyAction(){
$session = new Container('name');
$session->getManager()->destroy();
}
//the above codes are used for destroy the session.
To start a session you need to use
zend\session\container

Categories