For those developers who want to play with the classes and get a more intimate knowledge of composition, here’s the full code for the classes reviewed here. First, our “Page” class: class Page { And, second, the “Table” class: class Table { Also, here’s a possible implementation for the classes, in order to generate a basic page where its main content section includes a table with alternating row colors: // include the classes // instantiate a new Page object // make header // set Table object parameters // build body table // make footer // display page That’s all we need to make the classes work. As we usually do when working with classes, they’re included in the code. Then, we instantiate a “Page” object and build the page header, like this: require_once 'pageclass.php'; // instantiate a new Page object // make header Now, we simply pass to the “Table” object a range of numbers from 0 to 20, just to populate the main section of the page with some data, and assign an ID attribute to the table: // set Table object parameters Finally, we build the table, specifying the background colors that we want to be displayed alternately, generating the “footer” section, and displaying the page in the browser: $table->build('#ffcc00','#eeeeee'); // make footer // display page Now, we can say that our job is finally finished. With the classes working seamlessly, it’s time to read the conclusions and look ahead to the next article in this tutorial about composition. Just follow me. Wrapping up In this first part of the series, we’ve tasted the power of composition in PHP, building two basic classes that demonstrate in a didactical way how one object composes another. This is useful for getting you started quickly working with other interesting aspects of object-oriented programming. However, until now, we’ve worked merely with a couple of classes, which will hardly find their role in production environments. With this idea in mind, in the second part we’ll implement composition using a more realistic approach, since we’ll work with a fully functional MySQL abstraction class. Meanwhile, feel free to use the above developed code to introduce composition into your applications or develop your own classes. Until next time, stay tuned.
blog comments powered by Disqus |
|
|
|
|
|
|
|