I am trying to develop the most suitable design for passing session key between classes in PHP 5.3.
The session key is retrieved from a third-party API, and my application makes various API calls that require this session key to be passed.
I created classes to hold related API calls. For example, the basket directory contains methods that, when called, will send an API request to return data from calls such as API_GetCart (), API_AddItem (), etc.
I store the session key in a single cookie (the only cookie that is ever required) and I need to make the value of this cookie available to almost all of my classes. I cannot use a database or $ _SESSION to store session data. A third-party API is looking for session management for things like basket contents, etc.
When the user reaches my application for the first time, there will be no cookie value, so I will need to both assign a new session key to the new cookie and transfer this value (not yet available as a cookie, we are still processing one and same HTTP request) to other classes.
One of my ideas was to create a Session class like this and put the code grab / check code in the constructor.
class Session { public $sk; function __construct() { //code to check if user has sessionkey (sk) in cookie //if not, grab new sessionkey from 3rd party API and assign to new cookie // $sk = 'abcde12345'; //example $sk value } }
Then, on all the browsing pages, I would instantiate a new Session instance and then pass this object to each class that requires it (almost all), either as an argument to the class constructor, or as an argument to a method.
orderSummary.php
$s = new Session; //$s currently would only hold one variable, $sk = "abcde12345" //but in the future may hold more info or perform more work // what is best approach to making the sessionkey // available to all classes? arg to constructor or method... or neither :) $basket = new Basket; $baskSumm = $basket->getBasketSummary(); $billing = new Billing; $billSumm = $billing->getBillingSummary(); $delivery = new Delivery; $delSumm = $delivery->getDeliverySummary(); //code to render as HTML the customer basket details //as well as their billing and delivery details
Does the Session class (which really only contains one value) create a better idea? Given that he might need more values ββand perform a larger check, he felt "right", making him a class. As for passing this value to different classes, it would be better to pass the Session object to their constructor, for example.
$se = new Session; $basket = new Basket($se); $baskSumm = $basket->getBasketSummary();
I am new to OOP, so some recommendations will be greatly appreciated.