Object Oriented Programming with PHP 5 - More OOP

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    2 Favorites

    Object Oriented Programming with PHP 5 - More OOP - Presentation Transcript

    1. #3 Object Oriented Programming with PHP 5 More OOP Doc. v. 0.1 - 18/03/09 Wildan Maulana | wildan [at] tobethink.com
    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. Checking if a Class already exists • You can use class_exists() function <?php include_once(\"../ch2/emailer.class.php\"); if( class_exists(\"Emailer\")) { $emailer = new Emailer(\"hasin@pageflakes.com\"); } else { die(\"A necessary class is not found\"); } ?>
    4. Finding currently loaded Classes • You can use get_declared_classes() function. <?php include_once(\"../ch2/emailer.class.php\"); print_r(get_declared_classes()); ?>
    5. Finding out if Methods and Properties Exists • You can use method_exists() and property_exists() functions
    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,\"ChildClass\")) echo \"It's a ChildClass Type Object\"; echo \"\\n\"; if (is_a($cc,\"ParentClass\")) echo \"It's also a ParentClass Type Object\"; ?>
    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. 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(\"host=localhost password=pass user=username dbname=db\")) throw new Exception(\"Cannot connect to the database\"); } } $db = new db(); try { $db->connect(); } catch (Exception $e) { print_r($e); } ?>
    9. Collectiong all PHP Errors as Exception TODO
    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(\"dbname={$dbname} user={$user}\"); } 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. The Code In Action <?php $qi= new QueryIterator(\"golpo\",\"postgres2\",\"\"); $qi->exceute(\"select name, email from users\"); while ($qi->valid()) { print_r($qi->current()); $qi->next(); } ?>
    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(\"hasin\"=>\"hasin@pageflakes.com\", \"afif\"=>\"mayflower@phpxperts.net\", \"ayesha\"=>\"florence@pageflakes.net\")); $iterator = $users->getIterator(); while ($iterator->valid()) { echo \"{$iterator->key()}'s Email address is {$iterator->current()}\\n\"; $iterator->next(); } ?>
    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. ArrayObject() in Action <?php $users = new ArrayObject(array(\"hasin\"=>\"hasin@pageflakes.com\", \"afif\"=>\"mayflower@phpxperts.net\", \"ayesha\"=>\"florence@pageflakes.net\")); $iterator = $users->getIterator(); while ($iterator->valid()) { echo \"{$iterator->key()}'s Email address is {$iterator->current()}\\n\"; $iterator->next(); } ?>
    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(\"hasin\"=>\"hasin@pageflakes.com\", \"afif\"=>\"mayflower@phpxperts.net\", \"ayesha\"=>\"florence@pageflakes.net\")); echo $users->afif; ?>
    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']=\"mayflower@phpxperts.net\"; $users['hasin']=\"hasin@pageflakes.com\"; $users['ayesha']=\"florence@phpxperts.net\"; echo $users['afif'] ?>
    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 = \"Value One\"; $this->var2 = \"Value Two\"; $this->var3 = \"Value Three\"; SampleObject::$var4 = \"Value Four\"; } } $so = new SampleObject(); $serializedso =serialize($so); file_put_contents(\"text.txt\",$serializedso);
    18. Unserialize <?php include_once(\"sampleobject.class.php\"); $serializedcontent = file_get_contents(\"text.txt\"); $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. 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. 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. Object Cloning <?php PHP4 Output : Hasin $sample1 = new StdClass(); $sample1->name = \"Hasin\"; $sample2 = $sample1; $sample2->name = \"Afif\"; echo $sample1->name; PHP5 Output : Afif ?> If you wanna make deep copy in PHP5, you can use clone keyword <? $sample1 = new stdClass(); $sample1->name = \"Hasin\"; PHP5 Output : Hasin $sample2 =clone $sample1; $sample2->name = \"Afif\"; echo $sample1->name; ?>
    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(\"{$class}.class.php\"); } $s = new Emailer(\"hasin@somewherein.net\"); ?> Because of __autoload() function, PHP5 will auto load a file named class.emailer.php in the current directory
    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(\"id\",\"email\")­>from(\"user\")­>where(\"id=1\")                                         ­>limit(1)­>result();
    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 = \"SELECT \".join(\",\",$this­>selectables).\" FROM    }                                              {$this­>table}\";    public function where($clause)      if (!empty($this­>whereClause))    {      $query .= \" WHERE {$this­>whereClause}\";      $this­>whereClause = $clause;      if (!empty($this­>limit))      return $this;      $query .= \" LIMIT {$this­>limit}\";    }      echo \"The generated Query is : \\n\".$query;    public function limit($limit)    }    { }      $this­>limit = $limit; $db= new DBManager();      return $this; $db­>select(\"id\",\"name\")­>from(\"users\")­>where(\"id=1\")­>    }                                          limit(1)­>result(); ........ ?>    The output The generated Query is : SELECT id,name FROM users WHERE id=1 LIMIT 1
    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. Using memcached • Download and install the memcached first! <?php $memcache = new Memcache; $memcache->connect('localhost', 11211) or die (\"Could not connect\"); $tmp_object = new stdClass; $tmp_object->str_attr = 'test'; $tmp_object->int_attr = 12364; $memcache->set('obj', $tmp_object, false, 60*5) or die (\"Failed to save data at the server\"); ?> Restore the object.... <?php $memcache = new Memcache; $memcache->connect('localhost', 11211) or die (\"Could not connect\"); $newobj = $memcache->get('obj'); ?>
    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. Q&A
    29. Reference • Object Oriented Programming with PHP5, Hasin Hayder, PACKT Publishing

    + Wildan MaulanaWildan Maulana, 8 months ago

    custom

    3725 views, 2 favs, 1 embeds more stats

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 3725
      • 3716 on SlideShare
      • 9 from embeds
    • Comments 0
    • Favorites 2
    • Downloads 58
    Most viewed embeds
    • 9 views on http://wildanm.wordpress.com

    more

    All embeds
    • 9 views on http://wildanm.wordpress.com

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories

    Tags