1 / 44

PEAR Package

PEAR Package. Nikolay Kostov. Telerik Corporation. www.telerik.com. Summary. What is PEAR? Mail Database Authentication XML. What is PEAR?. PEAR is a set of classes and templates, available in the PHP distribution Provides large set of reusable components Object-oriented

jadyn
Download Presentation

PEAR Package

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. PEAR Package Nikolay Kostov Telerik Corporation www.telerik.com

  2. Summary • What is PEAR? • Mail • Database • Authentication • XML

  3. What is PEAR? • PEAR is a set of classes and templates, available in the PHP distribution • Provides large set of reusable components • Object-oriented • Aids and speeds up development • Fixes some cross-platform issues

  4. To install PEAR package management system execute C:\PHP\go-pear.bat Listing installed packages: Installing PEAR C:\>pear list INSTALLED PACKAGES, CHANNEL PEAR.PHP.NET: ========================================= PACKAGE VERSION STATE Mail 1.2.0b1 beta Mail_Mime 1.5.2 stable Mail_mimeDecode 1.5.0 stable Net_SMTP 1.3.2 stable Net_Socket 1.0.9 stable PEAR 1.7.2 stable Structures_Graph 1.0.2 stable

  5. To install a PEAR package you should know its name and version number Example: Installing PEAR package C:\>pear install Mail_Mime downloading Mail_Mime-1.5.2.tgz ... Starting to download Mail_Mime-1.5.2.tgz (22,176 bytes) ........done: 22,176 bytes downloading Mail_mimeDecode-1.5.0.tgz ... Starting to download Mail_mimeDecode-1.5.0.tgz (9,281 bytes) ...done: 9,281 bytes install ok: channel://pear.php.net/Mail_Mime-1.5.2 install ok: channel://pear.php.net/Mail_mimeDecode-1.5.0

  6. PEAR Public Web Site contains lots of open-source PEAR packages for free use http://pear.php.net/packages.php Contains package name, documentation, tutorials, examples, etc. PEAR packages are object-oriented Everyone can submit new packages for public use PEAR Public Web Site

  7. Mail Package • PHP provides the mail function • Uses sendmail program, available in Lunix/Unix systems • Works only with SMTP servers without encrypted authentication • PEAR Mail package allows sending trough SMTP servers, that require authentication, using IMAP, generates mails in MIME format, etc.

  8. Sending Mail • Sending email with PEAR is done in 3 steps: • Include the PEAR libraries • The Mail.php file is usually enough • Create new instance of the needed mail backend with the factory method • Supports "mail", "sendmail", "smtp" • Send the email with the send method

  9. Sending Mail with PEAR – Example require "Mail.php"; $body = "Как върви?"; $to = "Пешо <pe6o@parcuca.com>"; $headers = array ("Subject" => "Тема", "From"=>"Pesho<pesho@abv.bg>", "To" => $to, "Content-Type" => "text/plain; charset=UTF-8"; $smtpinfo = array ("host"=>"smtp.server.com", "port" => "25", "auth" => true, "username" => "smtp_user", "password" => "smtp_password"); $mail_obj=&Mail::factory("smtp", $smtpinfo); $mail_obj->send($to, $headers, $body);

  10. Mime Mails • The PEAR package also provides the Mail_mime class • Provides tools for sending emails with attachments, alternative content and etc. • Located in the Mail\mime.php file in the PEAR directory • The class is used only for generating the content of the mail, sending is handled the same way, as normal email

  11. Mime Mail – Example require "Mail.php"; require "Mail\mime.php"; $message = new Mail_mime(); $message->setTXTBody ("text body"); $message->setHTMLBody ("<html>…"); $message->addAttachment("\home\myfie.zip"); $body = $message->get(); $headers = $message->headers ( array ('From' => 'me@domain.com', 'To' => 'you@domain.com', 'Subject' => 'The zip file')); $mail=&Mail::factory ("smtp", …); $mail->send ('you@domain.com', $headers, $body); Generates the body of the email in MIME format Converts and adds headers in MIME format The sending is the same as normal email

  12. DB (MDB2) • DB is abstract layer for database handling • Newer version of PEAR merged it with other packages and renamed it to MDB2 • Object oriented approach • Emulates replace, sequence, prepare/execute and others if the RDBMS do not support it • Allows secure connection with SSL • Installing: • pearinstallMDB2MDB2_Driver_mysql

  13. DSN • DSN – Data Source Name • Address of data source, used by MDB2 to connect to it • Looks like URL • Can be provided as an array mysql://user:password@localhost/mydb ibase://sysdba:masterey@localhost//var/db.fdb phptype(dbsyntax)://username:password@protocol+hostspec/database?option=value

  14. Connecting the Database • MDB2 provides 3 methods • factory() – will instantiate the driver, but will not connect until required • Useful if application may not require DB connection at all • connect() – will immediately connect • singleton() – checks if connection is already established and returns reference to it • Better than creating global DB object

  15. Connecting the Database require_once "MDB2.php"; $dsn = array ( 'phptype' => 'mysql', 'username' => 'user', 'password' => 'mypass', 'database' => 'mydb'); $options = array (); $mdb = &MDB2::factory ($dsn, $options); if (PEAR::isError($mdb)) die ($mdb->getMessage()); • Second parameter is array with options • Can specify SSL state, result class to be used, debug level, etc

  16. The isError() method • PEAR and all classes in the package provide the isError() method • Static function • Checks if an object is PEAR error object • It is always clearer to call PEAR::isError instead of MDB2::isErrorfor example • This is stated by the PEAR developers • Each package provides the getMessage() method that returns text representation of last execution error

  17. Sending SQL Query • There are several methods for querying the database • All are methods of created MDB2 connection object (result of factory(), connect() or singleton() methods) • query() is the most direct, used for selecting data • Returns a new MDB2 result object or error object • exec() is used for modification queries • Returns number of affected rows or error

  18. Sending Query Example $mdb = &MDB2::factory ($dsn, $options); if (PEAR::isError($mdb)) die ($mdb->getMessage()); $res = &$mdb->query ("select * from foo"); if (PEAR::isError($res)) die ($res->getMessage()); $affected = &$mdb->exec("delete from foo"); if (PEAR::isError($affected)) die ($affected >getMessage()); • Notice $res->getMessage() and $affected->getMessage()

  19. Select Results • The object, returned from query method has several methods for fetching the data • fetchOne() – return single field from a column • fetchRow() – fetch entire row and move to next row • fetchCol(),fetchAll() – returns the data from all rows, respectively single or all columns

  20. Fetch Modes • MDB2 provides three modes for the data, returned by the fetch methods • Ordered – default way, arrays returned are with numeric indexes, same order as in the query • MDB2_FETCHMODE_ORDERED • Associative – indexes of the array are the names of the fields • MDB2_FETCHMODE_ASSOC • Object – returns object, instead of array, the properties names match the fields names • MDB2_FETCHMODE_OBJECT

  21. Fetch Modes • The fetch mode can be set with the setFetchMode method of the MDB2 object or can be supplied to the fetchRow method $mdb = &MDB2::factory ($dsn, $options); if (PEAR::isError($mdb)) die ($mdb->getMessage()); //set default fetch mode $mdb->setFetchMode(MDB2_FETCHMODE_OBJECT); $res = &$mdb->query ("select * from foo"); while ($row = &$res->fetchRow()) echo $row->id;

  22. More MDB2 • fetchRow() also can accept second parameter – the row number to fetch • The result object has several useful methods: • rowCount(), numCols() • getColumnNames() • seek() – jump to row in the result • MDB2 provides methods for working with BLOBs as streams

  23. Quoting and Escaping • MDB2 provides quote() method • Specific to the database • Formats the data accordingly • Important parameters • Data (some variable or value) • Data type (optional) , e. g. "integer", "text", "timestamp", etc. • The escape methods is similar but does not quote the value

  24. Quoting and Escaping • The example: • Will produce string like: $query = 'insert into employees (name, isWorking, dateHired, salary) values ('. $mdb->quote($name, 'text').', ', $mdb->quote($isWorking, 'boolean').', '. $mdb->quote($dateHired, 'date').', '. $mdb->quote($salary, 'integer').')'; insert into employees ( 'Jack', 1, '2008-01-03', 1000)

  25. PEAR Authentication • PEAR provides several simple class for authentication purposes • Uses database for storing the username and password information • Provides simple methods for checking valid user, registering, etc. • Downsides • Does not provide methods for user access levels • Does not provide automated way to store IP as part of the login data • Also provides classes for HTTP and RADIUS authentication

  26. PEAR Auth Object • All the authorization methods are in the Auth class • The constructor takes several parameters • Storage driver (usually database, identified by "DB") • Options array • Name of function that prints login form • Boolean: whether authentication is required • The start() method initializes the authentication process

  27. Auth Options • The constructor options are supplied as associative array • dsn – data source name, required • table – required when using database • usernamecol , passwordcol - the names of the columns that hold the user names and passwords • cryptType – the function used to encrypt the password (MD5, SHA, etc) • db_fields – comma separated list of fields that should be fetched with the user data • Can use * for all

  28. Auth methods • checkAuth – returns boolean, whether valid session authentication information exists • logout – closes the session • addUser – adds new user to the database • First two parameters are the username and password, the rest are optional and depend on the database structure • getAuthData() – returns extra information, stored in the Auth session

  29. Auth – Example $opt = array ( 'dsn' => 'mysql://user:pass@localhost/db', 'db_fields' => '*', 'usernamecol' => 'username', 'passwordcol' => 'pass'); // note the parameters supplied function loginfrm ($username = null, $status=null, &$auth=null) { echo "<form method=\"post\"… // it is required to send over post, // fields are named "username" and "password" } // continue to next slide

  30. Auth Example (2) // continue from previous slide $authobj = new Auth('DB', $opt, 'loginfrm'); $authobj->start(); if ($authobj->checkAuth()) { /* print data, visible only for registered users */ } else { echo 'Please, login';}

  31. Example Logout Page // continue from previous slide $authobj = new Auth('DB', $opt, 'loginfrm'); $authobj->start(); if ($authobj->checkAuth()) { $authobj->logout(); $authobj->start(); //not necessary}

  32. XML • PEAR provides packages for both parsing and serializing of XML data • Supports Unicode XML files • PHP has great support of reflection objects • Objects that create properties at runtime • This gives tools to easily turn XML into objects and vice-versa

  33. XML_Serializer • The PEAR XML_Serializer class is used to turn objects and arrays into XML • Main methods: • serialize ($data) – turns PHP data structure into XML, returns true or PEAR Error object • getSerializedData – returns the serialized XML document • setOptions – sets serializing options • Same options can be passed to the class constructor

  34. XML_Serializer options • addDecl – boolean, whether to add XML declaration "<?xml version… ?>" • encoding – sets document encoding • Added to the XML declaration too • defaultTagName – tag name used to serialize the values in indexed array • rootName – the name of the root tag • rootAttributes – associative array with attributes to add to the root tag

  35. XML_Serializer options • scalarAsAttributes – boolean, for associative arrays. If values in array are scalars they will be added as attributes of the tag • addDoctype – boolean, if doctype declaration should be added to the document • doctype – specify the URIs to be user in the DOCTYPE declaration • typeHints –sets if type/class info should be stored too

  36. Serializing – Example require_once 'XML/Serializer.php'; $palette = array ('red', 'green', 'blue'); $options = array ( "addDecl" => true, "encoding" => 'UTF-8', "rootName"=> 'palette', "defaultTagName" => 'color'); $serializer = new XML_Serializer($options); $serializer->serialize($palette); $xml = $serializer->getSerializedData(); <?xml version="1.0" encoding="UTF-8"?> <palette> <color>red</color> <color>green</color> <color>blue</color> </palette>

  37. Serializing Associative Array – Example … $data = array ( 'red' => 45, 'green' => 100, 'blue' => 80); … $serializer->serialize($data); … <?xml version="1.0" encoding="UTF-8"?> <palette> <red>45</red> <green>100</green> <blue>80<blue> </palette>

  38. XML_Unserialize • PEAR XML_Unserialize class parses XML data and returns nested associative and indexed arrays • Allows parsing to create objects instead of arrays • If the necessary classes are defined and there is class information in the XML • Unlike unserialize function does not have magic method to call (__wakeup)

  39. XML_Unserialize • Like the serializer class has one main method • unserialize ($data, $isFile, $options) • If $isFile is supplied as true, the class considers $data to be file name or stream resource to read the XML from • options can be supplied to the constructor, the unserialize method or via the setOptions method

  40. XML_Unserialize options • parseAttributes • If set to true tag attributes are parsed into arrays • attributesArray • The name of the array into which attributes data will be placed • tagMap • Allows mapping of XML tag to a PHP class to parse the data into

  41. Unserializing example <?xml version="1.0" encoding="UTF-8"?> <palette> <color>red</color> <color>green</color> <color>blue</color> </palette> $unserializer = new XML_Unserializer(); $unserializer->unserialize($xml); Array ( [color] => Array ( [0] => red [1] => green [2] => blue ) )

  42. Unserializing example • Using the same code • This time we get back the same data <?xml version="1.0" encoding="UTF-8"?> <palette> <red>45</red> <green>100</green> <blue>80<blue> </palette> Array ( [red] => 45 [green] => 100 [blue] => 80 )

  43. Install the following PEAR packages: MDB2, MDB2_Driver_mysql, Mail_Mime, XML_Serializer Using PEAR MDB2 implement the following: Connect to MySQL database Show all data from MySQL table Messages Insert new message Using XML_Serializer convert all messages from the database table Messages to XML file named messages.xml. Send the file messages.xml to your email as attachment. PEAR Package

  44. PEAR Package ? Questions? ? ? ? ? ? ? ? ? ? http://academy.telerik.com

More Related