Its a new feature that was introduce in PHP 5 that make you write more compact codes. i mean something like this
$obj -> methodA( ) -> methodB( ) -> methodc( ) -> result( );
The difference here compared to php 4 is that now, your method can now return objects, whether belonging to its own or another and gives a new dimension to thinking in objects.
May be because i am a zoologist, i will be used to describing my objects with animal world, permit me if that doesn't really go well with you but i am sure you will find it interesting.
Our object here for this example is a Fish. Thinking of a fish as an object, an animal that has the capability to swim in water. But first, let us write the old way you are used to;
// OLD FISH CLASS
<?php
class OldFish{
private $category; // A variable to represent if the fish has a jaw
private $scaletype; // Scale Type
private $name; // The name of the fish
public function setCategory($type)
{
$this -> category = $type;
$this -> category = $type;
}
public function setScaleType($scale)
{
$this -> scaletype = $scale;
$this -> scaletype = $scale;
}
public function setName($name)
{
$this -> name = $name;
$this -> name = $name;
}
public function printResult( )
{
$rtnstring = "Fish belongs to class" . $this -> category . "having a " . $this->scaletype . " scale type. Therefore The name of the fish is " . $this -> name;
echo $rtnstring;
}
}
Using the above class to create a fish
$fishobj = new OldFish;
$fishobj -> setCategory("Osteichthyes"); // give our fish a category
$fishobj -> setScaleType("Cycloid"); // give our fish a scale type
$fishobj -> setName("Tilapia"); // give our fish a name
$fishobj -> printResult( ); // Print out the result
THE OUTPUT LOOKS LIKE THIS:
Fish belongs to class Osteichthyes having a Cycloid scale type. Therefore the name of the fish is Tilapia.
You know this already, Yes, if i am right. Here all you have is an object of a fish that you are trying to give a catgeory, set the scale type and assign a name before you print out the result..You can have something more complex such that the details received will determine the name of the fish but let us leave it at this level for now. here no object is returned. Let us see method chaining, its not different from the code above but just by 3 lines of code changes everything. let us see.
//NEW FISH CLASS
class NewFish{
private $category; // A variable to represent if the fish has a jaw
private $scaletype; // Scale Type
private $name; // The name of the fish
public function setCategory($type)
{
$this -> category = $type;
$this -> category = $type;
return $this; // <= New Line Added to return the object
}
public function setScaleType($scale)
{
$this -> scaletype = $scale;
$this -> scaletype = $scale;
return $this; // <= New Line Added to return the object
}
public function setName($name)
{
$this -> name = $name;
$this -> name = $name;
return $this; // <= New Line Added to return the object
}
public function printResult( )
{
$rtnstring = "Fish belongs to class" . $this -> category . "having a " . $this->scaletype . " scale type. Therefore The name of the fish is " . $this -> name;
echo $rtnstring;
}
}
?>
Using the newFish class to create an object using a method chaining concept, we have:
<?php
$fishobj = new NewFish
$fishobj -> setCategory("Osteichthyes")
-> setScaleType("Cycloid")
-> setName("Tilapia")
-> printResult( );
?>
How does the above code works:
The same result is still printed, but objects were returned. A new fish object was created. when the setCategory is called, it returns $this; meaning set a value to the category field and return this current fishobject with a Category. At this point the scales and name has not been set, but already the fish object has a category. Until further set methods are called before the result is finally printed out all joined to one $fishobj (i.e the fish object without repeating in over and over.)
Because we can chain methods, they can be called more than once and in whatever order we like before the final function that returns the result or prints is called.
More complex example is seen below used for a generating a select Query of any type in mysql Database.
<?php
/**
* Code can be copied and remodied for other usages
*@author: Iginla Omotayo
*
* USING METHOD CHAINING PHP 5...SEE HOW TO USE BELOW
**/
class SelectQuery
{
private $selectables = array();
private $table;
private $whereClause;
private $limit;
private $conn;
private $query;
private $affected;
private $orderColumns;
private $sortby;
public function select()
{
$this->selectables=func_get_args();
return $this;
}
public function from($table)
{
$this->table = $table;
return $this;
}
public function where($clause)
{
$this->whereClause = $clause;
return $this;
}
public function limit($limit)
{
$this->limit = $limit;
return $this;
}
public function orderBy($cols,$desc_asc)
{
$this -> sortby = $desc_asc;
$this -> orderColumns = $cols;
return $this;
}
public function buildQuery()
{
$this->query = "SELECT ".join(",",$this->selectables)." FROM
{$this->table}";
if (!empty($this->whereClause))
{
$this->query .= " WHERE {$this->whereClause}";
}
if( (!empty($this->orderColumns)) && (!empty($this->sortby)) )
{
$this->query .= " ORDER BY {$this->orderColumns} $this->sortby";
}
if (!empty($this->limit))
{
$this->query .= " LIMIT {$this->limit}";
}
return $this;
}
public function getResult($conn)
{
$this->conn = $conn;
/* Select queries return a resultset */
$result = $this->conn -> query($this->query);
$this->affected = $conn->affected_rows;
if($result){ return $result; }else{ return false; }
}
public function getAffectedRows()
{
return $this->affected;
}
public function returnValue($column,$table,$wherecolumn,$wherevalue,$dconn)
{
$sql = "SELECT $column FROM $table WHERE $wherecolumn = '$wherevalue' LIMIT 1";
$sresult = $dconn -> query($sql);
while ($row = $sresult->fetch_assoc())
{
$rtnvalue = $row[$column];
}
return $rtnvalue;
}
}
?>
/**
* Code can be copied and remodied for other usages
*@author: Iginla Omotayo
*
* USING METHOD CHAINING PHP 5...SEE HOW TO USE BELOW
**/
class SelectQuery
{
private $selectables = array();
private $table;
private $whereClause;
private $limit;
private $conn;
private $query;
private $affected;
private $orderColumns;
private $sortby;
public function select()
{
$this->selectables=func_get_args();
return $this;
}
public function from($table)
{
$this->table = $table;
return $this;
}
public function where($clause)
{
$this->whereClause = $clause;
return $this;
}
public function limit($limit)
{
$this->limit = $limit;
return $this;
}
public function orderBy($cols,$desc_asc)
{
$this -> sortby = $desc_asc;
$this -> orderColumns = $cols;
return $this;
}
public function buildQuery()
{
$this->query = "SELECT ".join(",",$this->selectables)." FROM
{$this->table}";
if (!empty($this->whereClause))
{
$this->query .= " WHERE {$this->whereClause}";
}
if( (!empty($this->orderColumns)) && (!empty($this->sortby)) )
{
$this->query .= " ORDER BY {$this->orderColumns} $this->sortby";
}
if (!empty($this->limit))
{
$this->query .= " LIMIT {$this->limit}";
}
return $this;
}
public function getResult($conn)
{
$this->conn = $conn;
/* Select queries return a resultset */
$result = $this->conn -> query($this->query);
$this->affected = $conn->affected_rows;
if($result){ return $result; }else{ return false; }
}
public function getAffectedRows()
{
return $this->affected;
}
public function returnValue($column,$table,$wherecolumn,$wherevalue,$dconn)
{
$sql = "SELECT $column FROM $table WHERE $wherecolumn = '$wherevalue' LIMIT 1";
$sresult = $dconn -> query($sql);
while ($row = $sresult->fetch_assoc())
{
$rtnvalue = $row[$column];
}
return $rtnvalue;
}
}
?>
Imagine you have a table called [users] in your database, and fields called [id], and[ name]. To use the class above for a select query, simply see this.NOTE: db means database.
$conn = new mysqli("localhost", "db_user", "db_pass", "db_name");
$selectq = new SelectQuery();
// USING METHOD CHAINING TO QUERY
$selectq->from("users")->select("id","name")->limit(1)->where("id = '1'")->orderBy("name", "DESC")->buildQuery( )->getResult($conn);
$selectq->from("users")->select("id","name")->limit(1)->where("id = '1'")->orderBy("name", "DESC")->buildQuery( )->getResult($conn);
// FOR CLEARITY
$result_query = $selectq->from("users")
->select("id","name")
->limit(1)
->where("id
= '1'")
->orderBy("name",
"DESC")
->buildQuery( )
->getResult($conn);
You will see i used the 'limit function' before the 'where function', so the order does not matter.
In conclusion, What i saying in essence is, for as
long as $this is returned, The methods can be chained all together at
once....
No comments:
Post a Comment