I have a very simple random number generator. This number generator has a few options: you input a minimum and maximum number, form this number a random number will be generated. I store the maximum-minimum and generated number inside of a session to be used later while playing the game.
When we get redirected to the main page (the guess game) you have the option to guess the random number that is stored in the session from their one forth the game will give you feedback on how close you are etc.
My question boils down to this, an option of the game is to display all your previous guesses I had a basic idea of how I wanted to do this: I will store the current guess I did inside of an array this array will be linked to a session from which I can loop through all of the old guesses.
I have written a couple of functions to achieve this and it only stores the current guess overriding any number already stored in the array e.g. if my current guess is 6 this number will be stored inside the array, if I proceed to guess again for example 4 this number will be stored inside of the array but will override 6.
I hope my code examples will be more clear.
this function stores the old guesses inside of said array
public function Store_Old_Guesses_In_Session()
{
if (!isset($_SESSION["show_previous_guesses"])) {
return false;
}
if (isset($_POST["Guess_Button"])) {
return $_SESSION["old_guesses"] = $this->old_guesses = array(
"Old_guesses" => $this->getCurrentGuess(),
);
}
return false;
}
this function gets the current guess
public function getCurrentGuess()
{
if (isset($this->current_guess)) {
return $this->current_guess;
}
return false;
}
-
namespace Store;
use Get_Number\Get_Numbers;
require_once "Current_Guesses.php";
class Store_Numbers extends Get_Numbers
{
public array $old_guesses;
public function __construct()
{
parent::__construct();
if (isset($_SESSION["old_guesses"])) {
$this->old_guesses = $_SESSION["old_guesses"];
}
}
public function Store_Current_Number_In_Session()
{
if (empty($this->getCurrentNumber())) {
return false;
}
return $_SESSION["current_number"] = $this->getCurrentNumber();
}
public function Store_Minimum_Number_In_Session()
{
if (empty($this->getMinimumNumber())) {
return false;
}
return $_SESSION["minimum_number"] = $this->getMinimumNumber();
}
public function Store_Maximum_Number_In_Session()
{
if (empty($this->getMaximumNumber())) {
return false;
}
return $_SESSION["maximum_number"] = $this->getMaximumNumber();
}
public function Store_Checkbox_Value_In_Session()
{
if (empty($_POST["debug_options"])) {
return false;
}
return $_SESSION["debug_options"] = $_POST["debug_options"];
}
public function Store_show_previous_guesses_Checkbox_In_Session()
{
if (empty($_POST["show_previous_guesses"])) {
return false;
}
return $_SESSION["show_previous_guesses"] = $_POST["show_previous_guesses"];
}
public function Store_Current_Number_Checkbox_Value_In_Session()
{
if (empty($_POST["current_number_checkbox"])) {
return false;
}
return $_SESSION["current_number_checkbox"] = $_POST["current_number_checkbox"];
}
public function Store_Old_Guesses_In_Session()
{
if (!isset($_SESSION["show_previous_guesses"])) {
return false;
}
if (isset($_POST["Guess_Button"])) {
$this->old_guesses[] = $this->getCurrentGuess();
$_SESSION['old_guesses'] = array_push($this->old_guesses, $this->getCurrentGuess());
return $this->old_guesses;
}
return false;
}
}
I have a bunch of code examples should you need more
A few things you might need to know:
PHP = 7.4.2
The property $old_guesses is declared as an array like this public
array $old_guesses;
You need to push onto the array, not assign to it.
public function Store_Old_Guesses_In_Session()
{
if (!isset($_SESSION["show_previous_guesses"])) {
return false;
}
if (isset($_POST["Guess_Button"])) {
$this->old_guesses[] = $this->getCurrentGuess();
$_SESSION['old_guesses'] = $this->old_guesses;
return $this->old_guesses;
}
return false;
}
The constructor should initialize the variable from the session variable to make it persist and grow.
if (!isset($_SESSION['old_guesses'])) {
$_SESSION['old_guesses'] = array();
}
$this->old_guesses = $_SESSION['old_guesses'];
Related
I need opinion about using session with php. I'm useing session to store data. For instance - configuration:
First I'm loading data from config.ini to $_SESSION['config']
Then I'm using custom session class to get specific data from $_SESSION['config'][$key];
This is config function:
public static function load_config($process_sections = FALSE)
{
$array = parse_ini_file(CONFIG . DS . 'config.ini', $process_sections);
if ($array)
{
$_SESSION['configuration'] = $array;
return TRUE;
}
else
{
$_SESSION['configuration'] = array();
return FALSE;
}
}
function config($key, $default = NULL)
{
if (isset($_SESSION['configuration']))
{
if (isset($_SESSION['configuration'][$key]))
{
return $_SESSION['configuration'][$key];
}
else
{
return $default;
}
}
}
That same is with user object. I'm getting user data not from DB, but API, and storing it in $_SESSION['user']. When user object is constructs, I'm attributing all properties just from $_SESSION['user'][...], for instance:
public function __construct()
{
parent::__construct();
$this->initUser();
}
private function initUser()
{
if (Session::is('user'))
{
return $this->setUserData(Session::get('user'));
}
else
{
return FALSE;
}
}
private function setUserData($data)
{
foreach ($data as $key => $value)
{
if(property_exists($this->_name, $key))
{
$this->{$key} = $value;
}
}
return TRUE;
}
Properties are defined in class. I'm doing it just on time, when object is constructing. Is that right practice? It's working very good for me but I doubt if my method overolads server.
So I got this example layout.
private $_getMilk() = '';
public function getMilk():string {
return $this->_milk;
}
public function setMilk(string $milk) {
$this->_milk = $milk;
}
SetMilk is also used to empty milk which sounds weird to me why set empty string if you ask for milk.
Should I instead also create the function emptyMilk. (asume the milk property is getting called alot)
public function emptyMilk() {
$this->_milk = '';
}
A benefit of a seperate emptyMilk() function is that it allows you to use a special representation for an empty object, rather than exposing that to the callers.
private $is_empty = true;
public function getMilk(): string {
if ($this->$is_empty) {
throw new Exception("Empty milk");
}
return $this->$_milk;
}
public function setMilk(string $milk) {
$this->is_empty = false;
$this->_milk = $milk;
}
public function emptyMilk() {
$this->is_empty = true;
$this->_milk = null;
}
public function gotMilk(): boolean {
return !$this->is_empty;
}
This allows you to use any value for $_milk rather than making one value special.
What are the implications of
// Use a setData method to populate data on the object. This will allow data to be set multiple times with a single object
class Testy
{
private $data = [];
public function setData(array $data)
{
$this->data = $data;
}
public function validate()
{
foreach($this->data as $data) {
if (! isset($data['id'])) {
return false;
}
}
return true;
}
}
versus
// Set data using the constructor that will require multiple objects to handle multiple use cases
class Testy
{
private $data = [];
public function __construct(array $data)
{
$this->data = $data;
}
public function validate()
{
foreach($this->data as $data) {
if (! isset($data['id'])) {
return false;
}
}
return true;
}
}
versus
// Set data to be validated directly on the validate method. This is the most concise of the 3 but the class simply becomes a wrapper for the method which may be a smell that it belongs elsewhere.
class Testy
{
public function validate($data)
{
foreach($data as $data) {
if (! isset($data['id'])) {
return false;
}
}
return true;
}
}
To provide some context: the example is very simplified and each $data array will contain objects used for validation. I wanted to know in a scenario where this object might be used several times in a given request, which of the examples would be considered better and if there are any implications of any of the approaches listed.
Im not so experienced in php , Im using codeigniter to write my application , I have my own library and within my library there are three functions/methods that passes there arguments in one function which is in one of my models , my question is how will i manipulate/trick the method in my model to know exactly which function among the three in my library has passed the value and return the correct value ..
1st function
public function id_exist ($id) {
if(empty($id)) {
return FALSE;
}
return $this->library_model->this_exist($id);
}
2nd function
public function group_exist($group) {
if(empty($group)){
return FALSE;
}
return $this->library_model->this_exist($group);
}
with the 3rd same as the above 2
in my model
public function this_exist ($item) {
if(empty($item) || !isset($item)) {
return FALSE;
}
// here is where i need to know which function has passed the argument so that i can work with it and return the correct value from the database
}
Might be dirty, might be not sophisticated, but why not passing another argument which tells exactly the origin?
public function id_exist ($id) {
if(empty($id)) {
return FALSE;
}
return $this->library_model->this_exist('id', $id);
}
public function group_exist($group) {
if(empty($group)){
return FALSE;
}
return $this->library_model->this_exist('group', $group);
}
Model:
public function this_exist ($origin, $item) {
if(empty($item) || !isset($item)) {
return FALSE;
}
if($origin == 'id'){
// do something
}
elseif($origin == 'group') {
// do something else
}
}
Basically, what I want to do is create a class called Variables that uses sessions to store everything in it, allowing me to quickly get and store data that needs to be used throughout the entire site without working directly with sessions.
Right now, my code looks like this:
<?php
class Variables
{
public function __construct()
{
if(session_id() === "")
{
session_start();
}
}
public function __set($name,$value)
{
$_SESSION["Variables"][$name] = $value;
}
public function __get($name)
{
return $_SESSION["Variables"][$name];
}
public function __isset($name)
{
return isset($_SESSION["Variables"][$name]);
}
}
However, when I try to use it like a natural variable, for example...
$tpl = new Variables;
$tpl->test[2] = Moo;
echo($tpl->test[2]);
I end up getting "o" instead of "Moo" as it sets test to be "Moo," completely ignoring the array. I know I can work around it by doing
$tpl->test = array("Test","Test","Moo");
echo($tpl->test[2]);
but I would like to be able to use it as if it was a natural variable. Is this possible?
You'll want to make __get return by reference:
<?php
class Variables
{
public function __construct()
{
if(session_id() === "")
{
session_start();
}
}
public function __set($name,$value)
{
$_SESSION["Variables"][$name] = $value;
}
public function &__get($name)
{
return $_SESSION["Variables"][$name];
}
public function __isset($name)
{
return isset($_SESSION["Variables"][$name]);
}
}
$tpl = new Variables;
$tpl->test[2] = "Moo";
echo($tpl->test[2]);
Gives "Moo".