I have seen many questions on StackOverflow and I have this code
use Zend\Session\Container;
class IndexController extends AbstractActionController {
public function indexAction() {
$userSession = new Container('user');
$userSession->username = 'Sandhya';
return new ViewModel();
}
}
When I am printing the $userSession container in the controller it is giving me this output
Zend\Session\Container Object (
[name:protected] => user
[manager:protected] => Zend\Session\SessionManager Object (
[defaultDestroyOptions:protected] => Array (
[send_expire_cookie] => 1
[clear_storage] =>
)
[name:protected] =>
[validatorChain:protected] =>
[config:protected] => Zend\Session\Config\SessionConfig Object (
[phpErrorCode:protected] =>
[phpErrorMessage:protected] =>
[rememberMeSeconds:protected] => 240
[serializeHandler:protected] =>
[validCacheLimiters:protected] => Array (
[0] => nocache
[1] => public
[2] => private
[3] => private_no_expire
)
[validHashBitsPerCharacters:protected] => Array (
[0] => 4
[1] => 5
[2] => 6
)
[validHashFunctions:protected] =>
[name:protected] =>
[savePath:protected] =>
[cookieLifetime:protected] => 2592000
[cookiePath:protected] =>
[cookieDomain:protected] =>
[cookieSecure:protected] =>
[cookieHttpOnly:protected] => 1
[useCookies:protected] => 1
[options:protected] => Array (
[gc_maxlifetime] => 2592000
)
)
[defaultConfigClass:protected] => Zend\Session\Config\SessionConfig
[storage:protected] => Zend\Session\Storage\SessionArrayStorage Object (
)
[defaultStorageClass:protected] => Zend\Session\Storage\SessionArrayStorage
[saveHandler:protected] =>
)
[storage:protected] => Array ( )
[flag:protected] => 2
[iteratorClass:protected] => ArrayIterator
[protectedProperties:protected] => Array (
[0] => name
[1] => manager
[2] => storage
[3] => flag
[4] => iteratorClass
[5] => protectedProperties
)
)
It means there is nothing like username...
But when I am printing the S_SESSION it gives me this output...
Array (
[__ZF] => Array (
[_REQUEST_ACCESS_TIME] => 1429081041.81
)
[user] => Zend\Stdlib\ArrayObject Object (
[storage:protected] => Array (
[username] => Sandhya
)
[flag:protected] => 2
[iteratorClass:protected] => ArrayIterator
[protectedProperties:protected] => Array (
[0] => storage
[1] => flag
[2] => iteratorClass
[3] => protectedProperties
)
)
)
There is a field username...
But when I am trying to get the $_SESSION in view it gives me the same output as above..
The problem is I am not able to get the username in both the container as well as in $_SESSION.
I need it in the controllers.
what can be the problem need help? Thank you.
I think you have to work on your configuration.
You have to setup a common SessionManager to manage handling of your session information.
Something like this:
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions($config);
$sessionManager = new SessionManager($sessionConfig);
$sessionManager->start();
Container::setDefaultManager($sessionManager);
I would suggest registering your SessionManager config in your ServiceManager instance and then use it throughout the application.
'service_manager' => array(
'factories' => array(
'session_manager' => 'My\Factory\SessionManagerFactory'
)
)
You can then get your SessionManager in any controller:
$sessionManager = $this->serviceLocator->get('session_manager');
And if you create a new Container it will use your common/default SessionManager instance automatically so all will be managed in one place.
$userSession = new Container('user');
$userSession->getManager() === $this->serviceLocator->get('session_manager') // true
On how to register your session_manager I will refer to the official ZF2 documentation.
You can use the following code:
$userSession = new Container('user');
//To check the session variable in zf2:
if($userSession->offsetExists('username')){
//Your logic after check condition
}
This will return true or false on the basis of session exist or not.
//To get the value of session:
echo $user->offsetGet('username');
Above code will return the value of session index username.
Instead of $userSession->username = 'Sandhya'; you can use below code:
$user->offsetSet('username','Sandhya');
This is zf2 standard, which is used by session container in zf2.
you can just get your username from session in controllers.
$userSession = new Container('user');
$username = $userSession->username ;
var_dump($username); //Sandhya
it work for me . try it !
Related
Is it possible to set multiple session elements to the same session at different times? I have 2 classes and each class should set 2 session elements. What I'm getting back is an empty array. I am using session_start() on each page.
Also, I can set the session successfully from within a single class, but get an empty array back when setting from each class.
// User class
$_SESSION['user'] = array('id' => 1);
$_SESSION['user'] = array('name' => 'Tim Miller');
// Part class
$_SESSION['user'] = array('model' => '12311');
$_SESSION['user'] = array('part' => 'AA34F');
EDIT:
Here is the array I would like to create:
Array (
[user] => Array (
[id] => 1
[name] => Tim Miller
[model] => 12311
[part] => AA34F
[order] => 119026
[serial] => 12001923S3
)
)
Elements 0 and 1 should be set in the user class
Elements 2-3 should be set in the part class
Elements 4-5 should be set in the serial class
You can set it but bit different approach need to be used. You can create an array of sessions with different values.
You have to write session_start() on top of each file where you need to use session.
session_start();
// User class
$_SESSION['user'][] = array('id' => 1);
$_SESSION['user'][] = array('name' => 'Tim Miller');
// Part class
$_SESSION['user'][] = array('model' => '12311');
$_SESSION['user'][] = array('part' => 'AA34F');
print_r( $_SESSION['user'] );
Output looks like:
Array
(
[0] => Array
(
[id] => 1
)
[1] => Array
(
[name] => Tim Miller
)
[2] => Array
(
[model] => 12311
)
[3] => Array
(
[part] => AA34F
)
)
It's upto you how do you want to crate this array.
EDIT:
To get your desire format output and add values to array later in different files you can give a try like:
// Your code here!
session_start();
// User class
$_SESSION['user'][] = array('id' => 1, 'name' => 'Tim Miller');
// Part class
$key = -1
$key = array_search( 1, array_column($_SESSION['user'], 'id') );
// Here 1 in array_search is id of user your can use $id to add data to correct user's by id.
if( $key > -1 ) {
$_SESSION['user'][ $key ] = array_merge( $_SESSION['user'][ $key ], array('model' => '12311', 'part' => 'AA34F') );
}
print_r( $_SESSION['user'] );
This will give you following output:
Array
(
[0] => Array
(
[id] => 1
[name] => Tim Miller
[model] => 12311
[part] => AA34F
)
)
I am using CodeIgniter 2.2.6 + DataMapper, I have a question regarding how to transform the results of a stored procedure into DataMapper Models, then convert them to json.
I have a model called Event:
class Event extends DataMapper {
var $table = 'EVENT'; // map to EVENT table
}
with the following code, I can easily get the top 10 Event:
$event = new Event();
$event->get( 10, 0 );
$event->all_to_json(); //this convert the result to json following the table structure
Now I have a stored procedure getSpecialEvent(), the result of this SP has exactly same structure as Table EVENT,
With the followng code, I do get the content but they are in Array format:
$sql = "call getSpecialEvent()";
$event = new Event();
$event = $this->db->query ($sql);
print_r ($event->result_array());
this will returned some thing like this:
Array
(
[0] => Array
(
[event_id] => 11
[title] => Test1
...
)
[1] => Array
(
[event_id] => 2
[title] => Test1
...
)
)
if I use this
foreach ( $event as $obj ) {
print_r($obj);
}
I get empty array:
Array
(
)
Array
(
)
then I tried
print_r ($event->result());
it returns
Array
(
[0] => stdClass Object
(
[event_id] => 11
[title] => Test1
...
)
[1] => stdClass Object
(
[event_id] => 2
[title] => Test2
...
)
}
I used some code found on internet to cast stdClass Object to Event, it looks like ok, but when I call to_json() method, it doesn't work.
function objectToObject($instance, $className) {
return unserialize(sprintf(
'O:%d:"%s"%s',
strlen($className),
$className,
strstr(strstr(serialize($instance), '"'), ':')
));
}
foreach ( $event->result() as $obj ) {
$newObj = $this->objectToObject($obj, "Event");
print_r ($newObj);
print_r ($newObj->to_json());
}
I printed he casted object, here it is:
Event Object
(
[table] => EVENT
[error] =>
[stored] =>
[model] =>
[primary_key] => id
[valid] =>
[cascade_delete] => 1
[fields] => Array
(
)
[all] => Array
(
)
[parent] => Array
(
)
[validation] => Array
(
)
[has_many] => Array
(
)
[has_one] => Array
(
)
[production_cache] =>
[free_result_threshold] => 100
[default_order_by] =>
[_validated:protected] =>
[_force_validation:protected] =>
[_instantiations:protected] =>
[_field_tracking:protected] =>
[_query_related:protected] => Array
(
)
[_include_join_fields:protected] =>
[_force_save_as_new:protected] =>
[_where_group_started:protected] =>
[_group_count:protected] => 0
[event_id] => 11
[title] => test11
...
)
but $newObj->to_json() returns empty
Array
(
)
Array
(
)
if I do a small test
$event = new Event ();
$event->event_id = 13;
$event->title = "xxxxx";
echo json_encode($event->to_json());
I do get:
{"event_id":13,"title":"xxxxx"....}
I don't know why the casted object doesn't work with to_json?
It seems to be a limitation, the casted DataMapper object (Event here) is not taken as a real DataMapper object, then I create a method in Event to export the needed info to aother pure object model and use json_encode(), this works.
I'm accessing customer data from the Stripe API, which I'd like to convert to JSON. Usually I'd convert an object to an array and use json_encode() but I don't seem able to in this case, even when trying to access the nested arrays.
This is the response I'm trying to convert to json:
Stripe_Customer Object
(
[_apiKey:protected] => MY_KEY_IS_HERE
[_values:protected] => Array
(
[id] => cus_2dVcTSc6ZtHQcv
[object] => customer
[created] => 1380101320
[livemode] =>
[description] => Bristol : John Doe
[email] => someone6#gmail.com
[delinquent] =>
[metadata] => Array
(
)
[subscription] =>
[discount] =>
[account_balance] => 0
[cards] => Stripe_List Object
(
[_apiKey:protected] => MY_KEY_IS_HERE
[_values:protected] => Array
(
[object] => list
[count] => 1
[url] => /v1/customers/cus_2dVcTSc6ZtHQcv/cards
[data] => Array
(
[0] => Stripe_Object Object
(
[_apiKey:protected] => MY_KEY_IS_HERE
[_values:protected] => Array
(
[id] => card_2dVcLabLlKkOys
[object] => card
[last4] => 4242
[type] => Visa
[exp_month] => 5
[exp_year] => 2014
[fingerprint] => NzDd6OkHnfElGUif
[customer] => cus_2dVcTSc6ZtHQcv
[country] => US
[name] => John Doe
[address_line1] =>
[address_line2] =>
[address_city] =>
[address_state] =>
[address_zip] =>
[address_country] =>
[cvc_check] => pass
[address_line1_check] =>
[address_zip_check] =>
)
[_unsavedValues:protected] => Stripe_Util_Set Object
(
[_elts:Stripe_Util_Set:private] => Array
(
)
)
[_transientValues:protected] => Stripe_Util_Set Object
(
[_elts:Stripe_Util_Set:private] => Array
(
)
)
[_retrieveOptions:protected] => Array
(
)
)
)
)
[_unsavedValues:protected] => Stripe_Util_Set Object
(
[_elts:Stripe_Util_Set:private] => Array
(
)
)
[_transientValues:protected] => Stripe_Util_Set Object
(
[_elts:Stripe_Util_Set:private] => Array
(
)
)
[_retrieveOptions:protected] => Array
(
)
)
[default_card] => card_2dVcLabLlKkOys
)
[_unsavedValues:protected] => Stripe_Util_Set Object
(
[_elts:Stripe_Util_Set:private] => Array
(
)
)
[_transientValues:protected] => Stripe_Util_Set Object
(
[_elts:Stripe_Util_Set:private] => Array
(
)
)
[_retrieveOptions:protected] => Array
(
)
)
Any help greatly appreciated!
PHP has reserved all method names with a double underscore prefix for future use. See https://www.php.net/manual/en/language.oop5.magic.php
Currently, in the latest php-stripe library, you can convert the Stripe Object to JSON by simpl calling **->toJSON().
[PREVIOUSLY]
All objects created by the Stripe PHP API library can be converted to JSON with their __toJSON() methods.
Stripe::setApiKey("sk_xxxxxxxxxxxxxxxxxxxxxxxxx");
$customer = Stripe_Customer::create(array(
"card" => $token,
"plan" => $plan,
));
$customer_json = $customer->__toJSON();
There is also a __toArray($recursive=false) method. Remember to set true as argument otherwise you will get an array filled with stripe objects.
Stripe::setApiKey("sk_xxxxxxxxxxxxxxxxxxxxxxxxx");
$customer = Stripe_Customer::create(array(
"card" => $token,
"plan" => $plan,
));
$customer_array = $customer->__toArray(true);
The attributes of Stripe_Objects can be accessed like this:
$customer->attribute;
So to get the customer's card's last4, you can do this:
$customer->default_card->last4;
However, you'll need to make sure you have the default_card attribute populated. You can retrieve the default_card object at the same time as the rest of the customer by passing the expand argument:
$customer = Stripe_Customer::retrieve(array(
"id" => "cus_2dVcTSc6ZtHQcv",
"expand" => array("default_card")
));
On the latest version, You can use echo $customer->toJSON(); to get the output as JSON.
I have done this way
`Stripe::setApiKey("sk_xxxxxxxxxxxxxxxxxxxxxxxxx");
$stripe_response= Stripe_Customer::create(array(
"card" => $token,
"plan" => $plan,
));
//Encoding stripe response to json
$resposnse_json_ecoded= json_encode($stripe_response);
//decoding ecoded respose
$response_decoded = json_decode($resposnse_json_ecoded, true);
//get data in first level
$account_id=$response_decoded['id'];
$individual = $response_decoded['individual'];
//get data in second level
$person_id=$individual['id'];`
If, like me, you arrived here looking for the python 2.7 solution, simply cast the stripe_object to str(). This triggers the object's inner __str__() function which converts the object into a JSON string.
E.g.
charge = stripe.Charge....
print str(charge)
Your top level object contains other object instances - the cast to (array) affects only the top level element. You might need to recursively walk down - but I'd do it differently here given that the classes are serializable:
$transfer = serialize($myobject);
What are you going to do with the otherwise JSONified data?
If you're going to transfer an object without the class information you might try to use Reflection:
abstract class Object {
/**
* initialize an object from matching properties of another object
*/
protected function cloneInstance($obj) {
if (is_object($obj)) {
$srfl = new ReflectionObject($obj);
$drfl = new ReflectionObject($this);
$sprops = $srfl->getProperties();
foreach ($sprops as $sprop) {
$sprop->setAccessible(true);
$name = $sprop->getName();
if ($drfl->hasProperty($name)) {
$value = $sprop->getValue($obj);
$propDest = $drfl->getProperty($name);
$propDest->setAccessible(true);
$propDest->setValue($this,$value);
}
}
}
else
Log::error('Request to clone instance %s failed - parameter is not an object', array(get_class($this)));
return $this;
}
public function stdClass() {
$trg = (object)array();
$srfl = new ReflectionObject($this);
$sprops = $srfl->getProperties();
foreach ($sprops as $sprop) {
if (!$sprop->isStatic()) {
$sprop->setAccessible(true);
$name = $sprop->getName();
$value = $sprop->getValue($this);
$trg->$name = $value;
}
}
return $trg;
}
}
This is the base class of most of my transferrable classes. It creates a stdClass object from a class, or initializes a class from a stdClass object. You might easily adopt this to your own needs (e.g. create an array).
This is already in a JSON format so you do need to convert it again into json_encode()
just pass it into your script
I am trying to make my way through an inherited Yii Framework site. Very little Object Oriented knowledge previously.
I'm printing some user information to see what is there like this...
print_r(Yii::app()->user);
And that's printing out this...
CWebUser Object (
[allowAutoLogin] => 1
[guestName] => Guest
[loginUrl] => Array
(
[0] => /site/login
)
[identityCookie] =>
[authTimeout] => 7200
[autoRenewCookie] =>
[autoUpdateFlash] => 1
[loginRequiredAjaxResponse] =>
[_keyPrefix:CWebUser:private] => 7c6285462394c9a141b5d66dce54e8f2
[_access:CWebUser:private] => Array
(
[Admin] =>
[Judge] =>
[Student] => 1
)
[behaviors] => Array
(
)
[_initialized:CApplicationComponent:private] => 1
[_e:CComponent:private] =>
[_m:CComponent:private] =>
)
I'm trying to get out the information that this user is a Student. I see it! It's ]there!
[Student] => 1
But how would I get that information out?
UPDATE:
Here's the parts of CWebUser that appear to have something to do with _access
private $_access=array();
public function checkAccess($operation,$params=array(),$allowCaching=true)
{
if($allowCaching && $params===array() && isset($this->_access[$operation]))
return $this->_access[$operation];
$access=Yii::app()->getAuthManager()->checkAccess($operation,$this->getId(),$params);
if($allowCaching && $params===array())
$this->_access[$operation]=$access;
return $access;
}
The following should tell you whether the user has 'Student' access:
$isStudent = Yii::app()->user->checkAccess('Student') == 1;
'student' is part of the $_access array. But $_access is private so you can not access it directly.
But there must be a method (function) to get it!
look in the CWebUser class there should be a method like
getStudent();
isStudent();
or may be
$access = getAccess();
$access['student'];
Edit:
checkAccess
seems to be used someting like this checkAccess('student');
I am doing the login using twitter oauth functionality. I am getting the following object from $client = $token->getHttpClient($config) method:
Zend_Oauth_Client Object
(
[_config:protected] => Zend_Oauth_Config Object
(
[_signatureMethod:protected] => HMAC-SHA1
[_requestScheme:protected] => header
[_requestMethod:protected] => POST
[_version:protected] => 1.0
[_callbackUrl:protected] => http://roomstayssvn.com/register/twittercallback
[_siteUrl:protected] => http://twitter.com/oauth
[_requestTokenUrl:protected] =>
[_accessTokenUrl:protected] =>
[_authorizeUrl:protected] =>
[_consumerKey:protected] => b04fuaxLR2d035FN8tTkQ
[_consumerSecret:protected] => NGPPovdXDnSpivNoMNIgA609ZJIB8GVKGgs6yEF8A
[_rsaPrivateKey:protected] =>
[_rsaPublicKey:protected] =>
[_token:protected] => Zend_Oauth_Token_Access Object
(
[_params:protected] => Array
(
[oauth_token] => 299516752-tksjJZUR7Q2gwrDRDpLOLCrYhySTGWz1SBwTKcRU
[oauth_token_secret] => 7S9R2FLuB0GT4vvy0GerThUnpkbSTeSalURib48Sx20
[user_id] => 299516752
[screen_name] => jogkunal5
)
)
.....
..... and so on
I want to print user_id and screen_name. How can I print it?
Following should work
$user_id = $client->getToken()->getParam('user_id');
$screen_name = $client->getToken()->getParam('screen_name');
Zend_Oauth_Client::__call() proxies any method of Zend_Oauth_Config.
Zend_Oauth_Config::getToken() returns Zend_Oauth_Token
Zend_Oauth_Token::getParam() gets the value for a parameter
Read the docs from here.
Its better you use a Good IDE that supports Zend framework.