|
|
#1 |
|
Swine Buddy
Join Date: Apr 02
Location: Langley, Berks, UK Mode: Restructuring
Posts: 4,833
![]() ![]() ![]() ![]() ![]() ![]() ![]() |
Tutorial: PHP 5 OOP
PHP 5 OOP PHP 5 makes some significant improvements on the Object Orientated programming model of PHP 4, bringing it more in line with languages such as VB.NET and Java. The improved object model in PHP 5 makes developing applications using OOP much easier and gives you, the programmer greater flexibility. I hope to use these tutorials to introduce to you some of the new features of the PHP 5 object model as well as create something which you will find useful in the process. I have therefore chosen as a test case, a database abstraction layer, similar to the Pear DB abstraction layer, however, not as feature rich, remember this is only a tutorial. ![]() This thread is locked and I will add the next part of the tutorial on a regular basis, if you have any comments, criticisms, etc. about anything, please post them here. Contents
Introduction One of PHP's stronger areas is it's support for database connectivity. It is able to connect to and talk to just about any database server / interface you can imagine. However, with this comes a few inherent problems; each database system has its own features, functions and in most cases they have their own versions of SQL although the functions used to access these databases are similar they do vary subtly meaning that if you were to want to port an application written for MySql to MS SQL server, the refactoring would require for example manually changing all calls to mysql_query() to mssql_query(). While we are not going to go as far as developing our database independent version of SQL, we shall use the new features of PHP 5 to help us build a consistent database API with support for stored procedures where it is not already present. This can then make switching from one database system to another as painless as changing one line of code. Last edited by visualAd; Dec 29th, 2005 at 12:48 PM. |
|
|
|
|
#2 |
|
Swine Buddy
Join Date: Apr 02
Location: Langley, Berks, UK Mode: Restructuring
Posts: 4,833
![]() ![]() ![]() ![]() ![]() ![]() ![]() |
Interfaces Abstract Classes and the Adapter Pattern
Interfaces Abstract Classes and the Adapter Pattern
The first feature we will visit which is new to PHP 5, is abstract classes and interfaces. These concepts are nothing more than features added to OOP which force the programmer to follow good coding standards. Abstract Classes An abstract class is a class which is only partially implemented by the programmer. It may contain 1 or more abstract methods. An abstract method is simply a function definition and serves to tell the programmer that the method must be implemented in a child class. To create an abstract class we use the following: PHP Code:
PHP Code:
Interfaces An interface is similar to an abstract class, indeed the occupy the same namespace as classes and abstract classes, (hence you cannot define an interface with the same name as a class). An interface however, is a fully abstract class; none of its method are implemented and, instead of a class subclassing from it; it is said to implement that interface. We are going to use an interface in our database abstraction layer, to ensure that every time we create a class for a particular database, it exposes the same API. When using them, we can then rely on the methods defined in the interface being part of the class, because, if they are not, PHP will not parse it. We are going to take the MySql functions as an example as it is the most commonly used database amongst PHP programmers. The most commonly used functions are: mysql_connect() mysql_error() mysql_errno() mysql_query() mysql_fetch_array() mysql_fetch_row() mysql_fetch_assoc() mysql_fetch_object() mysql_num_rows() mysql_close() If all our database classes expose the same methods with the same return types we can be sure that changing from MySql to Postgre SQL will be painless. We therefore arrive at the following interface: PHP Code:
Notice how we have included an escape_string() method as a static method. This method does not require an active connection to a database and should not require and instance of any object which implements the DB interface. In my opinion, this is the single most important method of any database implementation; an poorly implemented escape string method could make your applications vulnerable SQL injection. PHP Code:
PHP Code:
PHP Code:
In this article you have seen how to protect and restrict the visibility of object data using the accessibility modifiers private, protected and public when declaring class variables. These modifiers are used in the MysqlDB and DBQuery classes to protect data important to the internal workings of the objects. In our next article I'll present another new feature in PHP 5, type hinting. You will also get to extend the DBQuery to allow for support of all the functions in the DB interface that operate on the result of an executed query. This will be accomplished using delegation. If you have any comments regarding this tutorial please post them here, not in this thread. Last edited by visualAd; Apr 24th, 2006 at 12:13 AM. |
|
|
|
|
#3 |
|
Swine Buddy
Join Date: Apr 02
Location: Langley, Berks, UK Mode: Restructuring
Posts: 4,833
![]() ![]() ![]() ![]() ![]() ![]() ![]() |
Protecting data with Visibility
Protecting Data With Visibility
You may have noticed in the previous example the use of the $link variable of the MySqlDB class. This variable is used to store the link resource generated when a connection is made to the MYSql database. You may also have noticed the word private before its declaration in contrast to the PHP 4 method of prefixing the variable using var. The word private refers to the visibility (also known as accessibility) of the variable within the class. Visibility is similar to variable scope, however, offers finer control. There are three types of visibility.
Similar to the implementation of interfaces, attempting to violate these rules in your program will generate a fatal error and, again, like interfaces, their existence is purely for the convenience of the programmer; this does not mean however they should be ignored. Specifying the visibility of your class member variables enables you to protect data within your objects from outside influence. The $link variable in the MySqlDB class is declared as private – this means that the variable can only be accessed from within the object using the $this variable preventing it from being overwritten accidentally by any other object or function outside the class. We will use the visibility tools to help us create a query object for our database abstraction layer. We can think of a query as an individual entity with text which is executed and a result aquired after its execution. It would be useful to keep these two attributes of a query in the same place, an object perhaps?? Some database systems also have a facility which provides stored procedures. Stored procedures are similar to functions; they are stored queries which can take parameters. Versions of MySql before 5.1 and some of database management systems do not however provide this feature. We will incorporate both of these features into our query object. It will emulate a basic stored procedure and store the result pointer internally. We will build on the query object in the next part of the article to tie it in properly with our database abstraction layer. For now we will work on just the query object, which we will simply call query the query() function of an object which implements the DB interface. We will define the following public functions in our query object:
Protected Members As mentioned above we can use the concept of visibility to hide the internal workings of our query object and protect the integrity of data required for its internal workings. We have already explained that we will be storing the result pointer returned by the query as a protected property. We use protected members, because a database specific query object which extends from our query object may need to override the core functionality. If you have any comments regarding this tutorial please post them here, not in this thread. Last edited by visualAd; Feb 6th, 2006 at 06:53 PM. |
|
|
|
|
#4 |
|
Swine Buddy
Join Date: Apr 02
Location: Langley, Berks, UK Mode: Restructuring
Posts: 4,833
![]() ![]() ![]() ![]() ![]() ![]() ![]() |
Protecting data with Visibility
Can I Hve Cod Pls!!!!
Enough theory, lets get coding. First we will create a template for our object and build from that. PHP Code:
We will build the prepare() function first. To ensure that no characters within quotes are accidentally parsed as place holders, we remove all strings and store them temporarily in an array. The strings themselves are also replaced with place holders identified by a sequence of characters which should never appear in an SQL statement. During compilation of the query, the procedure placeholders are first substituted, then the strings of put back into the query. We accomplish this with the help of the preg_replace() function and a helper, function, used as a callback of the preg_replace() function. PHP Code:
The Compile Function Next task is to build the compile() and execute() functions. The compile() function will:
PHP Code:
The Execute Function Finally, the execute() function. The execute() function compiles the query and then executes it using the DB object which was used to initialise the DBQuery object, notice how the call_user_func_array() function is used to get the compiled query: PHP Code:
A short Example To demonstrate how the query object may be used, i have constructed the a small example which uses the DBQuery object as a stored procedure in checking for a correct user name and password. PHP Code:
If you have any comments regarding this tutorial please post them here, not in this thread. Last edited by visualAd; Feb 10th, 2006 at 07:03 PM. |
|
|
|
|
#5 |
|
Swine Buddy
Join Date: Apr 02
Location: Langley, Berks, UK Mode: Restructuring
Posts: 4,833
![]() ![]() ![]() ![]() ![]() ![]() ![]() |
Re: Tutorial: PHP 5 OOP
Using Delegation and Type Hinting
Type Hinting is a new facility in PHP 5 which enables you to force function arguments to be objects of specific types. Before PHP 5, the only way of ensure that function arguments were of a specific object type was to use the type checking functions provided. Now we can simply enforce the object type by proceeding the function argument with its name. We have already seen type hinting in our DBQuery object, to ensure that an object which implements the DB interface is passed to the objects constructor. PHP Code:
Delegation At present our DBQuery object simply mimics (all be it – rather simply) a stored procedure. Once executed a result resource is returned which we must store and pass the MySqlDB object if we wish to use functions such as num_rows() or fetch_row() on the result set. Would it not be nice if the DBQuery object were able to implement the functions which the MySqlDB object implements, which are designed to work on the result of an executed query? Take the code in our previous example and let us assume that the DBQuery object now manages the result resource for us: PHP Code:
We are going to modify the DBQuery object to include all functions which work on a result resource from the DB object. We will use the result stored when the query is executed to invoke the corresponding function of the DB object and return its result. The following functions will be added: PHP Code:
|
|
|
|
|
#6 |
|
Swine Buddy
Join Date: Apr 02
Location: Langley, Berks, UK Mode: Restructuring
Posts: 4,833
![]() ![]() ![]() ![]() ![]() ![]() ![]() |
Using Deleation and Type Hinting
Throwing Exceptions
You may haven noticed from the above code that we are catching an exception called, QueryException (we will implement this object later). An exception is similar to an error however more generic. The best way to describe an exception is an emergency. While an emergency might not necessarily be fatal, it must be dealt with. When an exception is thrown in PHP, the current scope of execution is immediately terminated, whether it be a function, try..catch block or the script itself. The exception then travels up the calling stack terminating each execution scope until it is either caught in try..catch block or it reaches the top of the calling stack where it will generate a fatal error. Exception handling is another new feature in PHP 5 which, when used in conjunction with OOP, allows for fine control over error handling an reporting. A try..catch block acts as a mechanism to deal with an exception. Once caught, execution of the script continues from the next line of the scope from which the exception was caught and handled. We need to change our execute function to throw an exception, if the query fails. We will throw a custom exception object called, QueryException, which is passed the DBQuery object that caused the error. PHP Code:
In PHP we can throw any object as an exception, but as a rule of thumb the exception should extend PHP's built in exception class. By creating our own customer exception, we can record extra information about the nature of the error if any, create an entry in a log, in fact, you can do anything you like. Our custom exception will do several things:
PHP Code:
PHP Code:
If you have any comments regarding this tutorial please post them here, not in this thread. Last edited by visualAd; Apr 24th, 2006 at 12:14 AM. |
|
|
|
|
#7 |
|
Swine Buddy
Join Date: Apr 02
Location: Langley, Berks, UK Mode: Restructuring
Posts: 4,833
![]() ![]() ![]() ![]() ![]() ![]() ![]() |
The Template Pattern
The Template Pattern
One of the major concepts behind the object orientated methodology is code reuse. When coding their application developers are encouraged to split large pieces of functionality up into smaller objects, each designed to accomplish a specific task. These objects should be generic enough to be used in other applications. Our MysqlDB and DBQuery object are two examples of objects which are likely to be used in more than one application. The Template pattern modifies the logic of a class to make it more complete or more specific. Several examples of this have already been demonstrated earlier in this tutorial through the use of inheritance. The template pattern can also be used however to make create an instance specific class, which though the use of the constructor, initialises all the required properties. Let us take the MySqlDB object as an example. Before any of its functions can be used, the connect() function must be called and supplied the hostname, user name and password for the server. A database also needs to be select. The connection information will often remain constant in your application, therefore an object template can be created that extends the MySqlDB object. PHP Code:
PHP Code:
You can use the template pattern in this fashion has several advantages:
Creating an instance of the MySqlDB object and connecting to the database is now as simplae as: PHP Code:
In this series of articles I have taken you through new features provided by the PHP 5 object model and demonstrated how design patterns (methods of solving common OOP related problems) can be applied through PHP. You should now be equipped with the knowledge needed to effectively use PHP 5's new object model. In using it effectively, you will produce more efficient, scalable and robust applications, while making the job of coding it easier. If you have any comments regarding this tutorial please post them here, not in this thread.
__________________
PHP || MySql || Apache || Get Firefox || OpenOffice.org || Click || Slap ILMV || 1337 c0d || GotoMyPc For FREE! Part 1, Part 2 | PHP Session --> Database Handler * Custom Error Handler * Installing PHP * HTML Form Handler * PHP 5 OOP * Using XML * Ajax * Xslt | VB6 Winsock - HTTP POST / GET * Winsock - HTTP File Upload Latest quote: crptcblade - VB6 executables can't be decompiled, only disassembled. And the disassembled code is even less useful than I am. Random VisualAd: Spread happiness and joy. Rate good posts.
|
|
|
![]() |
|
||||||
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|