codeigniter is returning database row considered oop - php

im using Codeigniter 3.0 query builder, my question when ever my model return a user i'm returning a database row. not an object -its stdobject but not try object- is this anything related to oop practice ?
my auth model is simple
class user extend CI_MODEL{
funciton attempt($user,$pass){
//do validation and fetch user and compare pass etc...
$query = $this->db->get_where('users',$where);
return $query->result() //now this is my line of question
}
}
so i think this is nothing related to oop ? -or am i wrong ? - its just procedural code using classes for organization !.
so what is the correct way in oop manner ?
I have goan through many auth libraries for codeigntier to see how they do it, and all what i see is they save user row to an array variable in model. yet all users are still inside only 1 user object .
should i create an abstract class/interfaces for user object and pass database row to it every time i fetch a user before i save them to my Big ci_model ?
if so is this doable in codeigniter ? where would i put this abstract classes ?

I have done somthing like this, and yes I have created a model_row class to pass all data to in a array_walk style:
if ($qry = $this->db->get()) {
$res = $qry->result();
return $this->_instantiateRows($res);
}
Function _instantiateRows():
/**
* Get the row class name
* Checks if a class exists with the model name _Row
* #return string
*/
private function _getRowClass() {
$modelName = get_class($this);
return class_exists($modelName.'_Row') ? $modelName.'_Row' : 'Model_Row';
}
/**
* Formats results into model row classes
* #param array $results
* #return array
*/
protected function _instantiateRows($results) {
$rowClass = $this->_getRowClass();
$self = $this;
array_walk($results,function(&$row,$k) use ($rowClass, $self) {
$row = new $rowClass($row,$self,$k);
});
return $results;
}
Then a row class:
/**
* Model row class
* Acts as a baseclass and a fallback class for database rows
* Implements standard methods, for saving, getting the ID, and setting field
* values.
* #property $_model MY_Model
* #property $_key Original Array key
* #property $_ID_FIELD name of the id field
*/
class Model_Row
{
protected $_isNew = True;
protected $_model = False;
protected $_key = False;
protected $_ID_FIELD = 'id';
protected $_ID_ORIGINAL = False;
/**
* C'tor
* Sets up the object with data from the row
* #param object $data
* #param object $model
* #param int $key
* #param string $id_field
*/
public function __construct($data,$model,$key=False) {
$this->_key = $key;
// If no key is specified then it must be new / Not from database
if ($this->_key !== False)
$this->_isNew = False;
$data = (array)$data;
$this->_model = $model;
$this->_ID_FIELD = $model->idField;
$this->set($data);
// Ensure ID Field is set.
$idF = $this->_ID_FIELD;
if (!isset($this->$idF))
$this->$idF = null;
}
/**
* Get the ID field
* ID Field could be named differently for each model, this is an easy
* shortcut to it.
* #param string $setTo - set the id to this value
* #return string
*/
public function id($setTo=False) {
$idF = $this->_ID_FIELD;
if ($setTo !== False) {
if ($this->_ID_ORIGINAL === False && !$this->_isNew)
$this->_ID_ORIGINAL = $this->$idF;
$this->set($idF,$setTo);
}
return $this->$idF !== null ? (string)$this->$idF : False;
}
/**
* Save this row
* #return bool
*/
public function save() {
$wheres = array();
if (!$this->_isNew) {
$idF = $this->_ID_FIELD;
$wheres[$idF] = $this->_ID_ORIGINAL ?: $this->id();
}
$res = $this->_model->set($this,$wheres);
if ($this->id() === False)
$this->id($this->_model->insertID());
// Reset the original id field
$this->_ID_ORIGINAL = False;
$this->_isNew = False;
if ($res)
return $this;
return False;
}
/**
* Set object properties
* can be passed by array field => value
* #param mixed $field
* #param mixed $value
* #return null
*/
public function set($field,$value=False) {
if ((is_array($field) || is_object($field)) && $value === False) {
if (is_object($field))
$field = (array)$field;
foreach($field as $f => $v)
$this->set($f,$v);
}
else {
if (method_exists($this, 'set_'.$field))
call_user_func(array($this,'set_'.$field), $value);
else
$this->$field = $value;
}
}
}
The point of the _getRowClass is to check for a class called model_name_row if this exists, then instantiate the data to this class, otherwise fall back to the baseclass model_row
There are some other things your model will need too, because the row class will be passed the model, so your model will need a public $idField='id' , and then this function can be usefull on your model:
/**
* Create a new record using the model row class
* #param mixed $data
* #return Model_Row
*/
public function newRow($data=array()) {
$rowClass = $this->_getRowClass();
return new $rowClass($data,$this);
}
So you can do $newRow = $this->Model->newRow($data) which will create a new row, then can call $newRow->save() and other methods if set...
* EDIT
Also to point out, I use $this->_model->set($this, $wheres) on the row class, this is because I have defined a baseclass with a public setter:
/**
* Setter
* #param mixed $data object or array
* #param mixed $wheres object or array query
* #return bool
*/
public function set($data,$wheres=array()) {
if (!$this->checkTableSet())
return False;
if (empty($wheres)) {
return $this->db->insert($this->table,$data);
}
else {
$this->db->where($wheres);
return $this->db->update($this->table,$data);
}
}
$this->table is a model variable with the table name, e.g. protected $table='users'; and the function checkTableSet() simply checks whether this has been set and not empty..

Related

Initializing class properties

I need to initialize some properties in my class. I don't use constructor, only set methods.
<?php
namespace Task;
class Log {
private $_views = null;
private $_urls = null;
private $_traffic = null;
/**
* #param int $count
*/
public function setViewCount(int $count) {
$this->$_views = $count;
}
/**
* #return int
*/
public function getViewCount() {
return $this->$_views;
}
/**
* #param int $count
*/
public function setUrlCount(int $count) {
$this->$_urls = $count;
}
/**
* #return int
*/
public function getUrlCount() {
return $this->$_urls;
}
/**
* #param int $trafficData
*/
public function setTraffic(int $trafficData) {
$this->$_traffic = $trafficData;
}
/**
* #return int
*/
public function getTraffic() {
return $this->$_traffic;
}
}
?>
Then I try to set values to properties and save it to associative array.
<?php
require 'Log.php';
use Task;
$log = new Task\Log();
$log->setViewCount(44);
$log->setUrlCount(55);
$log->setTraffic(99999);
$res = array("views" => $log->getViewCount(), "urls" => $log->getUrlCount(), "traffic" => $log->getTraffic());
echo json_encode($res);
?>
After encoding to json I see that any element of array has last value I set to object. In this example last is 99999 for Traffic so I got {"views":99999,"urls":99999,"traffic":99999}. What's the reason of such behaviour and how can I get correct values in each element of array?
$this->$_views this accesses not the field named _views but a field with the name stored in variable $_views.
Since you have no such variable the name assumed empty, thus the same name for each of setters or getters.
In short: you need to remove $ after ->:
$this->_urls = $count;
etc.

How to set _models and _keys for BaseDataProvider

<?php
/**
* #link http://www.yiiframework.com/
* #copyright Copyright (c) 2008 Yii Software LLC
* #license http://www.yiiframework.com/license/
*/
namespace yii\data;
use Yii;
use yii\base\Component;
use yii\base\InvalidParamException;
/**
* BaseDataProvider provides a base class that implements the [[DataProviderInterface]].
*
* #property integer $count The number of data models in the current page. This property is read-only.
* #property array $keys The list of key values corresponding to [[models]]. Each data model in [[models]] is
* uniquely identified by the corresponding key value in this array.
* #property array $models The list of data models in the current page.
* #property Pagination|boolean $pagination The pagination object. If this is false, it means the pagination
* is disabled. Note that the type of this property differs in getter and setter. See [[getPagination()]] and
* [[setPagination()]] for details.
* #property Sort|boolean $sort The sorting object. If this is false, it means the sorting is disabled. Note
* that the type of this property differs in getter and setter. See [[getSort()]] and [[setSort()]] for details.
* #property integer $totalCount Total number of possible data models.
*
* #author Qiang Xue <qiang.xue#gmail.com>
* #since 2.0
*/
abstract class BaseDataProvider extends Component implements DataProviderInterface
{
/**
* #var string an ID that uniquely identifies the data provider among all data providers.
* You should set this property if the same page contains two or more different data providers.
* Otherwise, the [[pagination]] and [[sort]] may not work properly.
*/
public $id;
private $_sort;
private $_pagination;
private $_keys;
private $_models;
private $_totalCount;
/**
* Prepares the data models that will be made available in the current page.
* #return array the available data models
*/
abstract protected function prepareModels();
/**
* Prepares the keys associated with the currently available data models.
* #param array $models the available data models
* #return array the keys
*/
abstract protected function prepareKeys($models);
/**
* Returns a value indicating the total number of data models in this data provider.
* #return integer total number of data models in this data provider.
*/
abstract protected function prepareTotalCount();
/**
* Prepares the data models and keys.
*
* This method will prepare the data models and keys that can be retrieved via
* [[getModels()]] and [[getKeys()]].
*
* This method will be implicitly called by [[getModels()]] and [[getKeys()]] if it has not been called before.
*
* #param boolean $forcePrepare whether to force data preparation even if it has been done before.
*/
public function prepare($forcePrepare = false)
{
if ($forcePrepare || $this->_models === null) {
$this->_models = $this->prepareModels();
}
if ($forcePrepare || $this->_keys === null) {
$this->_keys = $this->prepareKeys($this->_models);
}
}
/**
* Returns the data models in the current page.
* #return array the list of data models in the current page.
*/
public function getModels()
{
$this->prepare();
return $this->_models;
}
/**
* Sets the data models in the current page.
* #param array $models the models in the current page
*/
public function setModels($models)
{
$this->_models = $models;
}
/**
* Returns the key values associated with the data models.
* #return array the list of key values corresponding to [[models]]. Each data model in [[models]]
* is uniquely identified by the corresponding key value in this array.
*/
public function getKeys()
{
$this->prepare();
return $this->_keys;
}
/**
* Sets the key values associated with the data models.
* #param array $keys the list of key values corresponding to [[models]].
*/
public function setKeys($keys)
{
$this->_keys = $keys;
}
/**
* Returns the number of data models in the current page.
* #return integer the number of data models in the current page.
*/
public function getCount()
{
return count($this->getModels());
}
/**
* Returns the total number of data models.
* When [[pagination]] is false, this returns the same value as [[count]].
* Otherwise, it will call [[prepareTotalCount()]] to get the count.
* #return integer total number of possible data models.
*/
public function getTotalCount()
{
if ($this->getPagination() === false) {
return $this->getCount();
} elseif ($this->_totalCount === null) {
$this->_totalCount = $this->prepareTotalCount();
}
return $this->_totalCount;
}
/**
* Sets the total number of data models.
* #param integer $value the total number of data models.
*/
public function setTotalCount($value)
{
$this->_totalCount = $value;
}
/**
* Returns the pagination object used by this data provider.
* Note that you should call [[prepare()]] or [[getModels()]] first to get correct values
* of [[Pagination::totalCount]] and [[Pagination::pageCount]].
* #return Pagination|boolean the pagination object. If this is false, it means the pagination is disabled.
*/
public function getPagination()
{
if ($this->_pagination === null) {
$this->setPagination([]);
}
return $this->_pagination;
}
/**
* Sets the pagination for this data provider.
* #param array|Pagination|boolean $value the pagination to be used by this data provider.
* This can be one of the following:
*
* - a configuration array for creating the pagination object. The "class" element defaults
* to 'yii\data\Pagination'
* - an instance of [[Pagination]] or its subclass
* - false, if pagination needs to be disabled.
*
* #throws InvalidParamException
*/
public function setPagination($value)
{
if (is_array($value)) {
$config = ['class' => Pagination::className()];
if ($this->id !== null) {
$config['pageParam'] = $this->id . '-page';
$config['pageSizeParam'] = $this->id . '-per-page';
}
$this->_pagination = Yii::createObject(array_merge($config, $value));
} elseif ($value instanceof Pagination || $value === false) {
$this->_pagination = $value;
} else {
throw new InvalidParamException('Only Pagination instance, configuration array or false is allowed.');
}
}
/**
* Returns the sorting object used by this data provider.
* #return Sort|boolean the sorting object. If this is false, it means the sorting is disabled.
*/
public function getSort()
{
if ($this->_sort === null) {
$this->setSort([]);
}
return $this->_sort;
}
/**
* Sets the sort definition for this data provider.
* #param array|Sort|boolean $value the sort definition to be used by this data provider.
* This can be one of the following:
*
* - a configuration array for creating the sort definition object. The "class" element defaults
* to 'yii\data\Sort'
* - an instance of [[Sort]] or its subclass
* - false, if sorting needs to be disabled.
*
* #throws InvalidParamException
*/
public function setSort($value)
{
if (is_array($value)) {
$config = ['class' => Sort::className()];
if ($this->id !== null) {
$config['sortParam'] = $this->id . '-sort';
}
$this->_sort = Yii::createObject(array_merge($config, $value));
} elseif ($value instanceof Sort || $value === false) {
$this->_sort = $value;
} else {
throw new InvalidParamException('Only Sort instance, configuration array or false is allowed.');
}
}
/**
* Refreshes the data provider.
* After calling this method, if [[getModels()]], [[getKeys()]] or [[getTotalCount()]] is called again,
* they will re-execute the query and return the latest data available.
*/
public function refresh()
{
$this->_totalCount = null;
$this->_models = null;
$this->_keys = null;
}
}
The code above is the BaseDataProvider for yii2. My question is how i can set the _models and _keys in yii2? Which file do i need to change to link to that? Sorry i am quite new to yii. Please provide an example if possible thank you.
That what's You pasted here is abstract Yii2 class, which You should NEVER edit.
To use this thing i suggest You to read about ActiveDataProvider here: Docs
$query = Post::find()->where(['status' => 1]);
$provider = new ActiveDataProvider([
'query' => $query,
]);
Here's an example how to use it, first line defines data which will be used to populate ActiveDataProvider (it's a SQL query), and then You create ActiveDataProvider instance with query as config parameter.

What is the best way to create Update Method using PHP OOP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have thinking of this from past an hour, but unable to understand the best way to add update, Insert feature using a class in PHP.
I have an employee table which has around 5 columns, so i have created different properties for it in my Employees Class.
Now i am unable to understand where to set these Values, in __costructor(), in add_employees() method or some other way..
If i set them in __constructor() then user must remember and follow the same pattern in writing arguments that i followed in writing the parameters.
I am unable to understand that is it a right way or should i use different approach to do this.
I have searched this on net, and found very complex examples, where people are taking argument in form of array, separating it, add loop in it and then put it into database.
Class Employees(){
public $db;
public $conn;
public $emp_id;
public $first_name;
public $last_name;
public $gender;
public $added_by;
public function __construct(){
$this->db= new DatabaseConnection('localhost', 'root', '', 'employeesmanagement');
$this->conn= $this->db->connectDb();
}
public function get_employees(){
}
public function add_employees(){
}
I've written a class before, that does only things related to database things. Here is the class
/**
* CLASS: Database
*
* Description: This class deals with all database connection
* across the website. If any class needs to use the database
* it has to extends this one.
*
* #author: Andre Ferraz
* #copyright: ^
* #version: 2.0
*/
class Database
{
/**
* Holds Class Object instance
*
* #var Object
* #access: Private
* #static
*/
private static $_instace;
/**
* Holds PDO Object
*
* #var PDO
* #access: Private
*/
private $_pdo;
/**
* Used to keep track of how many columns
* has been found!
*
* #var int
* #access: Private
*/
private $_count;
/**
* Holds data from database
*
* #var array
* #access: Private
*/
private $_results = array();
/**
* Description: Instantiates PDO object
*
* #access: Protected
*/
protected function __construct()
{
$host = Config::get("database:host");
$user = Config::get("database:username");
$pass = Config::get("database:password");
$dbna = Config::get("database:dbname");
try
{
$this->_pdo = new PDO("mysql:dbname=".$dbna.";host=".$host.";", $user, $pass);
}
catch(PDOException $e)
{
Redirect::to(500);
}
}
/**
* Description: Gets data from the database
*
* #access: protected
* #return boolean
*/
protected function get($table, $columns, $condition = null)
{
if($condition != null)
{
$query = $this->_pdo->prepare("SELECT $columns FROM $table WHERE $condition");
if($query->execute())
{
$this->_count = $query->rowCount();
if($this->_count > 0)
{
$this->_results = $query->fetchAll();
return true;
}
return false;
}
}
return false;
//#todo condition == null
}
/**
* Description: Very similar to get function, but
* instead it just checks if data exists without storing
* any data.
*
* #access: protected
* #return boolean
*/
protected function query($table, $columns, $condition = null)
{
if($condition != null)
{
$query = $this->_pdo->prepare("SELECT $columns FROM $table WHERE $condition");
if($query->execute())
{
$this->_count = $query->rowCount();
return(($this->_count > 0)? true : false);
}
}
return false;
//#todo condition == null
}
/**
* Description: Updates information on the database
*
* #access: protected
*/
protected function update($table, $CV = array(), $condition)
{
if($CV !=null)
{
$columns = '';
$x = 1;
foreach($CV as $key => $value)
{
$columns .= "$key='$value'";
if($x < count($CV))
{
$columns .= ",";
}
$x++;
}
$query = $this->_pdo->prepare("UPDATE $table SET $columns WHERE $condition");
if($query->execute())
return true;
else
return false;
}
return false;
}
/**
* Description: Inserts data into database
*
* #access: protected
*/
protected function insert($table, $CV = array())
{
if($CV !=null)
{
// Join array elements with a string
$columns = implode(", ", array_keys($CV));
$values = '';
$x = 1;
// Put array key values into variables
foreach($CV as $value)
{
$values .= "'".$value."'";
if($x < count($CV))
{
$values .= ', ';
}
$x++;
}
$query = $this->_pdo->prepare("INSERT INTO $table ($columns) VALUES({$values})");
// Check execution is successful
if($query->execute())
return true;
else
return false;
}
return false;
}
/**
* Description: Deletes data from the database
*
* #access: protected
*/
protected function delete($table, $condition = null)
{
if($condition != null)
{
$query = $this->_pdo->prepare("DELETE FROM $table WHERE $condition");
if($query->execute())
return true;
else
return false;
}
else
{
$query = $this->_pdo->prepare("DELETE FROM $table");
if($query->execute())
return true;
else
return false;
}
}
protected function getResults()
{
return $this->_results;
}
/**
* Description: Singleton pattern, prevents multiple
* instantiations of the same class.
*
* NOTE: This is not needed. Only for "show of"
*
* #access: public
* #static
* #return Object
*/
public static function instance()
{
if(isset(self::$_instace))
return self::$_instace;
else
self::$_instace = new self;
}
}
Which other classes like User class would extend and use all the necessary function from the database to get data related to the user. Have a look at the project. There are some bugs in a few classes (which I can't be bothered to fix at this point), but database class is working fine. I don't mind if you get reference from it.
Visit my github for the full project.
Github

Using one class's properties in another OOP PHP

I have the following class
namespace PG\Referrer\Single\Post;
class Referrer implements ReferrerInterface
{
/**
* #var $authorReferrer = null
*/
protected $isAuthorReferrer = null;
/**
* #var $dateReferrer = null
*/
protected $isDateReferrer = null;
/**
* #var $searchReferrer = null
*/
protected $isSearchReferrer = null;
/**
* #var $taxReferrer = null
*/
protected $isTaxReferrer = null;
/**
* #param array $values = null;
*/
public function __construct(array $values = null)
{
if ($values)
$this->setBulk($values);
}
/**
* Bulk setter Let you set the variables via array or object
*/
public function setBulk($values)
{
if (!is_array($values) && !$values instanceof \stdClass) {
throw new \InvalidArgumentException(
sprintf(
'%s needs either an array, or an instance of \\stdClass to be passed, instead saw %s',
__METHOD__,
is_object($values) ? get_class($values) : gettype($values)
)
);
}
foreach ($values as $name => $value) {//create setter from $name
global $wp_query;
if (array_key_exists($value, $wp_query->query_vars)) { //Check that user don't set a reserved query vars
throw new \InvalidArgumentException(
sprintf(
'%s is a reserved query_vars and cannot be used. Please use a unique value',
$value
)
);
}
$setter = 'set' . $name;
$condition = isset($_GET[$value]);
if ($setter !== 'setBulk' && method_exists($this, $setter)) {
$this->{$setter}($condition);//set value (bool)
}
}
return $this;
}
/**
* #param bool $authorReferrer
* #return $this
*/
public function setAuthorReferrer($isAuthorReferrer)
{
$this->isAuthorReferrer = $isAuthorReferrer;
return $this;
}
/**
* #param bool $dateReferrer
* #return $this
*/
public function setDateReferrer($isDateReferrer)
{
$this->isDateReferrer = $isDateReferrer;
return $this;
}
/**
* #param bool $searchReferrer
* #return $this
*/
public function isSearchReferrer($isSearchReferrer)
{
$this->isSearchReferrer = $isSearchReferrer;
return $this;
}
/**
* #param bool $taxReferrer
* #return $this
*/
public function setTaxReferrer($isTaxReferrer)
{
$this->isTaxReferrer = $isTaxReferrer;
return $this;
}
}
with its interface
namespace PG\Referrer\Single\Post;
interface ReferrerInterface
{
/**
* #param array $values
* #return $this
*/
public function setBulk($values);
/**
* #param bool $authorReferrer
* #return $this
*/
public function setAuthorReferrer($isAuthorReferrer);
/**
* #param bool $dateReferrer
* #return $this
*/
public function setDateReferrer($isDateReferrer);
/**
* #param bool $searchReferrer
* #return $this
*/
public function isSearchReferrer($isSearchReferrer);
/**
* #param bool $taxReferrer
* #return $this
*/
public function setTaxReferrer($isTaxReferrer);
}
This class sets up 4 conditionals that I need to use in another class. The values that is used in this class is also set from the other class, so basically the user sets values in the other class (lets call it class b) that is then used by class Referrer and returns the 4 conditionals which is then used by class b.
The reason why I'm doing it this way is because there will be two other classes that will need to do the same, but will returns different info
What is the more correct way to achieve this?
EDIT
To clear this up
class Referrer
The properties $isAuthorReferrer, $isDateReferreretc will either have a value of null or a boolean value depending on what is set by the user.
Example:
$q = new Referrer(['authorReferrer' => 'aq']);
In the code above, $isAuthorReferrer is set via the setBulk() method in the class to true when the variable aq is available in the URL or false when not present. The three other properties will return null because they are not set in the example.
The above works as expected, but I need to do this in another class, lets again call it class b. The arguments will be set to class b, and in turn, class b will set this arguments to class Referrer, class Referrer will use this arguments and return the proper values of its properties, and class b will use this results to do something else
Example:
$q = new b(['authorReferrer' => 'aq']);
Where class b could be something like this (it is this part that I'm not sure how to code)
class b implements bInterface
{
protected $w;
protected $other;
public function __construct($args = [])
{
//Do something here
// Do something here so that we can use $other in other classes or functions
}
public function a()
{
$w = new Referrer($args);
}
public function b()
{
// use $w properties here
// return $other for usage in other classes and functions
}
}
The best way is to inject the referrer to your classes in order to do loose coupling between them and the referrer (this pattern use the benefit of your ReferrerInterface):
class b implements bInterface
{
protected $referrer;
public function __construct(ReferrerInterface $referrer, array $values = array())
{
$this->referrer = $referrer;
$this->referrer->setBulk($values);
}
public function getReferrer()
{
return $this->referrer;
}
public function b()
{
// use $this->referrer properties here
}
}
// Instantiation (use your dependency injection if you have one):
$referrer = new Referrer();
$b = new b($referrer, ['authorReferrer' => 'aq']);
I do not understand what is $other so I removed it but explain me if you want me to I add it again.
If you need to use the properties of the referrer in b, you should add some getters in your ReferrerInterface to allow that. I would use setAuthorReferrer($isAuthorReferrer) to set the value and isAuthorReferrer() to get it for instance.

Which is the best way to display 'flash messages' in kohana v3?

I would like to know the best way to display flash messages in Kohana v3?
Some tutorials or examples would be helpful.
Do you mean like Kohana 2.x's flash session variables?
The latest Kohana supports get_once() which is pretty similar to the old flash session variables.
$session = Session::instance();
$session->set('test', 'Hello, World!');
// The session variable is returned and removed.
$test = $session->get_once('test');
I think the get_once is a great function, but what if you want to keep the data actually separate from the regular data, here's a basic class that overloads "Session" so that you can use "codeigniter" style flashdata calls with any data-store.
<?php defined('SYSPATH') or die('No direct script access.');
abstract class Session extends Kohana_Session {
/**
* This calls the parent Kohana_Session constructor and processes
* new flashdata to flashdata, and flashdata to old flashdata
*
* #param array configuration
* #param string session id
* #return void
* #uses Kohana_Session::__construct
*/
public function __construct(array $config = NULL, $id = NULL)
{
parent::__construct($config,$id);
if(array_key_exists('___of',$this->_data)){
//Remove old Flash data
unset($this->_data['___of']);
}
if(array_key_exists('___flash',$this->_data)){
//Move current last requests flash data to old flash data
$this->_data['___of'] = $this->_data['___flash'];
unset($this->_data['___flash']);
}
if(array_key_exists('___nf',$this->_data)){
//Move Last Requests added data to the flash data
$this->_data['___flash'] = $this->_data['___nf'];
unset($this->_data['___nf']);
}
}
/**
* keeps a variable set in the sessions flashdata array.
*
* $session->set_flashdata('foo', 'bar');
*
* #param string variable name
* #param ...
* #return $this
*/
public function keep_flashdata($k)
{
$args = func_get_args();
if(array_key_exists('___of',$this->_data)){
foreach($args as $key){
if(array_key_exists($key,$this->_data['___of'])){
//So we were going to trash it...
$this->set_flashdata($k,$this->_data['___of'][$key],true);
}
}
}
$this->_data['___nf'][$key] = $value;
return $this;
}
/**
* Set a variable in the sessions flashdata array.
*
* $session->set_flashdata('foo', 'bar');
*
* #param string variable name
* #param mixed value
* #return $this
*/
public function set_flashdata($key, $value, $current=false)
{
if(!array_key_exists('___nf',$this->_data)){
$this->_data['___nf'] = array();
}
$this->_data['___nf'][$key] = $value;
if($current){
if(!array_key_exists('___flash',$this->_data)){
$this->_data['___flash'] = array();
}
$this->_data['flash'][$key] = $value;
}
return $this;
}
/**
* Set a variable by reference in the sessions flashdata array.
*
* $session->bind_flashdata('foo', $foo);
*
* #param string variable name
* #param mixed referenced value
* #return $this
*/
public function bind_flashdata($key, & $value)
{
if(!array_key_exists('___nf',$this->_data)){
$this->_data['___nf'] = array();
}
$this->_data['___nf'][$key] =& $value;
return $this;
}
/**
* Removes a variable in the session array.
*
* $session->delete_flashdata('foo');
*
* #param string variable name
* #param ...
* #return $this
*/
public function delete_flashdata($key)
{
$args = func_get_args();
if(array_key_exists('___nf',$this->_data)){
foreach ($args as $key)
{
if(array_key_exists($key,$this->_data['___nf'])){
unset($this->_data['___nf'][$key]);
}
}
}
return $this;
}
/**
* Get a variable from the sessions flashdata array.
*
* $foo = $session->get_flashdata('foo');
*
* #param string variable name
* #param mixed default value to return
* #return mixed
*/
public function get_flashdata($key, $default = NULL)
{
if(array_key_exists('___flash',$this->_data) && array_key_exists($key,$this->_data['___flash'])){
return $this->_data['___flash'][$key];
} else if(array_key_exists('___nf',$this->_data) && array_key_exists($key,$this->_data['___nf'])){
return $this->_data['___nf'][$key];
}
return $default;
}
/**
* Get and delete a variable from the session array.
*
* $bar = $session->get_once('bar');
*
* #param string variable name
* #param mixed default value to return
* #return mixed
*/
public function get_flashdata_once($key, $default = NULL)
{
$value = $this->get_flashdata($key, $default);
if(array_key_exists($key, $this->_data['___flash'])){
unset($this->_data['___flash'][$key]);
}
if(array_key_exists($key, $this->_data['___nf'])){
unset($this->_data['___nf'][$key]);
}
return $value;
}
}
?>
I realize there was an answer to this, and like i stated before, the get_once method is great and all, but i enjoy auto garbage collection much more.
If you have any improvements on this code, let me know, its been great to me so far.
Have a look at this module, it might be what you are looking for https://github.com/daveWid/message
I've written a really simple class for this once. Check it out below. Usage examples below
class Notice {
private static $session;
private static $initialized = false;
// current notices
private static $notices = array();
function __construct() {
}
static function init() {
self::$session = Session::instance();
self::$notices['current'] = json_decode(self::$session->get_once('flash'));
if(!is_array(self::$notices['current'])) self::$notices['current'] = array();
self::$initialized = true;
}
static function add($notice, $key=null) {
if(!self::$initialized) self::init();
if(!is_null($key)) {
self::$notices['new'][$key] = $notice;
} else {
self::$notices['new'][] = $notice;
}
self::$session->set('flash', json_encode(self::$notices['new']));
return true;
}
static function get($item = null) {
if(!self::$initialized) self::init();
if($item == null) {
return self::$notices['current'];
}
if(!array_key_exists($item, self::$notices['current']))
return null;
return self::$notices['current'][$item];
}
}
Examples (provided this class is saved as APPPATH . 'classes/notice.php'):
Notice::add('Something great has happened!');
Notice::add('Exciting! I\'ve got something to tell you!', 'message');
echo Notice::get('message'); // "Exciting! I've got ..."
foreach(Notice::get() as $message) {
echo $i++ . $message .'<br />';
}
EDIT: funny... for some reason this question popped up somewhere, didn't notice it was a really old one... sorry for that!
I am using https://github.com/synapsestudios/kohana-notices in my project and I am very happy with it.

Categories