As I said in the section that you just read, the best way to understand how to use the chainable “orderby()” method created in the previous section is by way of a concrete example. Therefore, below I included a simple code sample that shows how to fetch some ordered records from a MySQL table by using the aforementioned method. Look at it: try { $db = new MySQL('host', 'user', 'password', 'database'); // fetch result set by chaining methods of MySQL class $result = $db->select('properties')->where("title LIKE 'c%'")->orderby('title DESC')->fetch(); while ($row = mysqli_fetch_object($result)){ echo $row->title . $row->description. '<br />'; } } catch(Exception $e) { echo $e->getMessage(); exit(); } As you can see, the previous code snippet first connects to MySQL, and then retrieves a group of rows from a “properties” MySQL table. Naturally, the most important detail to note here is that the retrieval query has been built by chaining three different methods of the “MySQL” class. Hopefully, this short example will give you a clear idea of how useful method chaining can be for building tight and compact APIs in PHP 5. As with many of my articles on PHP development, feel free to tweak all of the code samples included in this tutorial, which surely will arm you with a more solid knowledge of how to use this programming approach. Final thoughts In this fifth part of the series, I extended the existing functionality of the sample MySQL abstraction class by adding to it another chainable method, for creating the ORDER BY portion of SELECT statements. In the forthcoming installment, I’m going to finish building this class by defining two final methods. The first one will be tasked with creating the LIKE part of a query, while the second one will be responsible for returning Singletons of the class. So here’s my recommendation: don’t miss the next tutorial!
blog comments powered by Disqus |
|
|
|
|
|
|
|