Object Oriented Programming with PHP 5 - More OOP


Published on

Published in: Technology
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Object Oriented Programming with PHP 5 - More OOP

  1. 1. #3 Object Oriented Programming with PHP 5 More OOP Doc. v. 0.1 - 18/03/09 Wildan Maulana | wildan [at] tobethink.com
  2. 2. Class Information Functions • Checking if a Class already exists • Finding currently loaded classes • Finding out if Methods and Properties exists • Checking the type of Class • Finding out the Class name
  3. 3. Checking if a Class already exists • You can use class_exists() function <?php include_once(quot;../ch2/emailer.class.phpquot;); if( class_exists(quot;Emailerquot;)) { $emailer = new Emailer(quot;hasin@pageflakes.comquot;); } else { die(quot;A necessary class is not foundquot;); } ?>
  4. 4. Finding currently loaded Classes • You can use get_declared_classes() function. <?php include_once(quot;../ch2/emailer.class.phpquot;); print_r(get_declared_classes()); ?>
  5. 5. Finding out if Methods and Properties Exists • You can use method_exists() and property_exists() functions
  6. 6. Checking the Type of Class • You can use is_a() function to check the type of a class <?php class ParentClass { Its a ChildClass Type Object } Its also a ParentClass Type Object class ChildClass extends ParentClass { } $cc = new ChildClass(); output if (is_a($cc,quot;ChildClassquot;)) echo quot;It's a ChildClass Type Objectquot;; echo quot;nquot;; if (is_a($cc,quot;ParentClassquot;)) echo quot;It's also a ParentClass Type Objectquot;; ?>
  7. 7. Finding out the Class name • You can use get_class() function <?php class ParentClass { } class ChildClass extends ParentClass { } $cc = new ChildClass(); echo get_class($cc) ?>
  8. 8. Exception Handling • One of the most improved features in PHP5 is that you can now use exceptions, like other OOP languages out there. PHP5 introduces these exception to simplify error management <?php //class.db.php error_reporting(E_ALL - E_WARNING); class db { function connect() { if (!pg_connect(quot;host=localhost password=pass user=username dbname=dbquot;)) throw new Exception(quot;Cannot connect to the databasequot;); } } $db = new db(); try { $db->connect(); } catch (Exception $e) { print_r($e); } ?>
  9. 9. Collectiong all PHP Errors as Exception TODO
  10. 10. <?php class QueryIterator implements Iterator Iterators { private $result; private $connection; private $data; private $key=0; • An Iterator is a new private $valid; command introduce in function __construct($dbname, $user, $password) { PHP5 to help traversing $this->connection = pg_connect(quot;dbname={$dbname} user={$user}quot;); } through any object public function exceute($query) { $this->result = pg_query($this->connection,$query); if (pg_num_rows($this->result)>0) $this->next(); } public function rewind() {} public function current() { return $this->data; } public function key() { return $this->key; } public function next() { if ($this->data = pg_fetch_assoc($this->result)) { $this->valid = true; $this->key+=1; } else $this->valid = false; } public function valid() { return $this->valid; } } ?>
  11. 11. The Code In Action <?php $qi= new QueryIterator(quot;golpoquot;,quot;postgres2quot;,quot;quot;); $qi->exceute(quot;select name, email from usersquot;); while ($qi->valid()) { print_r($qi->current()); $qi->next(); } ?>
  12. 12. ArrayObject • Another useful object introduced in PHP5 is ArrayObject() that wraps the regular PHP array and gives it an OO flavor. You can programmatically access the array in an OO style <?php $users = new ArrayObject(array(quot;hasinquot;=>quot;hasin@pageflakes.comquot;, quot;afifquot;=>quot;mayflower@phpxperts.netquot;, quot;ayeshaquot;=>quot;florence@pageflakes.netquot;)); $iterator = $users->getIterator(); while ($iterator->valid()) { echo quot;{$iterator->key()}'s Email address is {$iterator->current()}nquot;; $iterator->next(); } ?>
  13. 13. ArrayObject() Methods Append() • This method can add any value at the end of the collection GetIterator() • This method simply creates an Iterator object and return so that you can perform iteration using Iteration style. This is very useful method for getting an Iterator object from any array OffsetExists() • The method can determine whether the specified offset exists in the collection OffsetGet() • This method returns the value for specified offset OffsetSet() • Like offsetGet(), this method can set any value to the specified index() OffsetUnset() • This method can unset the element at the specified index
  14. 14. ArrayObject() in Action <?php $users = new ArrayObject(array(quot;hasinquot;=>quot;hasin@pageflakes.comquot;, quot;afifquot;=>quot;mayflower@phpxperts.netquot;, quot;ayeshaquot;=>quot;florence@pageflakes.netquot;)); $iterator = $users->getIterator(); while ($iterator->valid()) { echo quot;{$iterator->key()}'s Email address is {$iterator->current()}nquot;; $iterator->next(); } ?>
  15. 15. Array to Object <?php class ArrayToObject extends ArrayObject { public function __get($key) { return $this[$key]; } public function __set($key,$val) { $this[$key] = $val; } } ?> <?php $users = new ArrayToObject(array(quot;hasinquot;=>quot;hasin@pageflakes.comquot;, quot;afifquot;=>quot;mayflower@phpxperts.netquot;, quot;ayeshaquot;=>quot;florence@pageflakes.netquot;)); echo $users->afif; ?>
  16. 16. <?php Accessing Objects in class users implements ArrayAccess { Array Style private $users; public function __construct() { $this->users = array(); } public function offsetExists($key) { return isset($this->users[$key]); } public function offsetGet($key) { return $this->users[$key]; } public function offsetSet($key, $value) { $this->users[$key] = $value; } public function offsetUnset($key) { unset($this->users[$key]); } } $users = new users(); $users['afif']=quot;mayflower@phpxperts.netquot;; $users['hasin']=quot;hasin@pageflakes.comquot;; $users['ayesha']=quot;florence@phpxperts.netquot;; echo $users['afif'] ?>
  17. 17. Serialization • Serialization is a process of persisting the state of an object in any location, either physical files or in variables. <?php class SampleObject { public $var1; private $var2; The script will output a string, which PHP understands how to unserialize. protected $var3; static $var4; public function __construct() { $this->var1 = quot;Value Onequot;; $this->var2 = quot;Value Twoquot;; $this->var3 = quot;Value Threequot;; SampleObject::$var4 = quot;Value Fourquot;; } } $so = new SampleObject(); $serializedso =serialize($so); file_put_contents(quot;text.txtquot;,$serializedso);
  18. 18. Unserialize <?php include_once(quot;sampleobject.class.phpquot;); $serializedcontent = file_get_contents(quot;text.txtquot;); $unserializedcontent = unserialize($serializedcontent); print_r($unserializedcontent); ?> Ouput Remember : We can't save SampleObject Object the state of a static variables ( by serializing [var1] => Value One [var2:private] => Value Two [var3:protected] => Value Three )
  19. 19. Magic Methods in Serialization • PHP5 provides two magic methods to hook in process of serialization : – __sleep <?php class ResourceObject { – __awake private $resource; private $dsn; public function __construct($dsn) { $this->dsn = $dsn; $this->resource = pg_connect($this->dsn); } public function __sleep() { pg_close($this->resource); return array_keys( get_object_vars( $this ) ); } public function __wakeup() { $this->resource = pg_connect($this->dsn); } } ?>
  20. 20. Object Cloning • PHP5 introduces a new approach while copying objects from one into another, which is quite different to PHP4. – PHP4 → deep copy – PHP5 → shallow copy
  21. 21. Object Cloning <?php PHP4 Output : Hasin $sample1 = new StdClass(); $sample1->name = quot;Hasinquot;; $sample2 = $sample1; $sample2->name = quot;Afifquot;; echo $sample1->name; PHP5 Output : Afif ?> If you wanna make deep copy in PHP5, you can use clone keyword <? $sample1 = new stdClass(); $sample1->name = quot;Hasinquot;; PHP5 Output : Hasin $sample2 =clone $sample1; $sample2->name = quot;Afifquot;; echo $sample1->name; ?>
  22. 22. Autoloading Classes or Classes on Demand • While working with big projects, another very good practice is loading classes only when you need it. That means you shouldn't over consume the memory by loading unnecessary classes all the time. <?php function __autoload($class) { include_once(quot;{$class}.class.phpquot;); } $s = new Emailer(quot;hasin@somewherein.netquot;); ?> Because of __autoload() function, PHP5 will auto load a file named class.emailer.php in the current directory
  23. 23. Method Chaining • Method chaining is another process introduced in PHP5 by which you can directly access the methods and attributes of an object when it is returned by any function $SomeObject­>getObjectOne()­>getObjectTwo()­>callMethodOfObjectTwo(); Or in a real life .... $dbManager­>select(quot;idquot;,quot;emailquot;)­>from(quot;userquot;)­>where(quot;id=1quot;)                                         ­>limit(1)­>result();
  24. 24. <?php class DBManager {    private $selectables = array();    private $table;    private $whereClause;    private $limit;    public function select()    {      $this­>selectables=func_get_args();      return $this;    }    public function from($table) ........     { public function result()      $this­>table = $table;    {      return $this;      $query = quot;SELECT quot;.join(quot;,quot;,$this­>selectables).quot; FROM    }                                              {$this­>table}quot;;    public function where($clause)      if (!empty($this­>whereClause))    {      $query .= quot; WHERE {$this­>whereClause}quot;;      $this­>whereClause = $clause;      if (!empty($this­>limit))      return $this;      $query .= quot; LIMIT {$this­>limit}quot;;    }      echo quot;The generated Query is : nquot;.$query;    public function limit($limit)    }    { }      $this­>limit = $limit; $db= new DBManager();      return $this; $db­>select(quot;idquot;,quot;namequot;)­>from(quot;usersquot;)­>where(quot;id=1quot;)­>    }                                          limit(1)­>result(); ........ ?>    The output The generated Query is : SELECT id,name FROM users WHERE id=1 LIMIT 1
  25. 25. Life cycle of an Object in PHP and Object Caching • An object is live until the script ends. As soon as the script finishes executing, any object instantiated by this script also dies • Unlike web tier in Java, there is no global or application- level scope in PHP • But there is some object caching technology available for PHP, the most successful among them is memcached (http://danga.com/memcached.)
  26. 26. Using memcached • Download and install the memcached first! <?php $memcache = new Memcache; $memcache->connect('localhost', 11211) or die (quot;Could not connectquot;); $tmp_object = new stdClass; $tmp_object->str_attr = 'test'; $tmp_object->int_attr = 12364; $memcache->set('obj', $tmp_object, false, 60*5) or die (quot;Failed to save data at the serverquot;); ?> Restore the object.... <?php $memcache = new Memcache; $memcache->connect('localhost', 11211) or die (quot;Could not connectquot;); $newobj = $memcache->get('obj'); ?>
  27. 27. Summary • In this presentation we learned how to use some advanced OOP concepts in PHP. We learned how to retrieve information from any object, and learned about ArrayAccess, ArrayObject, Iterators, and some other native objects which simplifies the life of a developer. Another very important thing we learned is Exception Handling. In next presentation we will learn about design patterns and how to use them in PHP. Happy Learning .. @_@
  28. 28. Q&A
  29. 29. Reference • Object Oriented Programming with PHP5, Hasin Hayder, PACKT Publishing