Tuesday 18 June 2013
Facebook StumbleUpon Twitter Google+ Pin It

Weird properties of PHP's lexer and parser

There are (as of PHP 5.3.0) only two tokens which represent a single character:
  • T_NAMESPACE_SEPARATOR: \
  • T_CURLY_OPEN: {
    • This only occurs inside of interpolated strings, e.g. "{$foo}" lexes to: '"' T_CURLY_OPEN T_VARIABLE '}' '"'
  • Technically, there is a third, T_BAD_CHARACTER, but it is non-specific. No longer true according to one of the php devs
There are two items in the parser which, instead of being unspecified and generating a generic parse error, exist only to throw a special parse error:
  • using isset() with something other than a variable
  • using __halt_compiler() anywhere other than the global scope (e.g., inside a function, conditional or loop)
(Shameless blog plug on this one) The closing tag ?> is implicitly converted to a semicolon. The opening tag consumes one character of whitepace (or two in case of windows newlines) after the literal tag, but is otherwise completely ignored by the parser. Thus, the following code is syntactically correct:
for ( $i = 0 ?><?php $i < 10 ?><?php ++$i ) echo "$i\n" ?>
And it lexes (after the first round transform) to
T_FOR '(' T_VARIABLE '=' T_LNUMBER ';' T_VARIABLE '<' T_LNUMBER ';'
          T_INC T_VARIABLE ')' T_ECHO '"' T_VARIABLE 
              T_ENCAPSED_AND_WHITESPACE '"' ';'
The next several relate to variable interpolation syntax. For these, it helps to know the difference between a statement (ifforwhile, etc) and an expression (something with a value, like a variable, object lookup, function call, etc).
  1. If you interpolate an array with a single element lookup and no braces, non-identifier-non-whitespace chars will be parsed as single-character tokens until either a whitespace character or closing bracket is encountered.
    • e.g., "$foo["bar$$foo]" lexes to '"' T_VARIABLE '[' '"' T_STRING '$' '$' T_STRING ']' '"'
  2. In a similar scenario to the above, if you do use a space inside the braces, you will get an extra, emptyT_ENCAPSED_AND_WHITESPACE token.
    • e.g., "$foo[ whatever here" lexes to '"' T_VARIABLE '[' T_ENCAPSED_AND_WHITESPACE T_ENCAPSED_AND_WHITESPACE '"'
  3. In the midst of complex interpolation, if you are in one of the constructs that allows you to use full expressions, you can insert a closing tag (which PHP considers to be the same as a ';' and therefore bad syntax, but nevertheless), and it will be parsed as such. Furthermore, if you use an open tag, the lexer will remember that you were in the middle of an expression inside a string interpolation, although this seems like a moment of good design and implementation (or something like it).
You can nest heredocs. Seriously. Consider the following:
echo <<<THONE
${<<<THTWO
test
THTWO
}
THONE;
You can nest it as deep as you want, which is terrible (edit: a terrible thing to do), but what is hilarious is that, while the actual PHP interpreter handles this scenario correctly, the PHP userland tokenizer, token_get_all(), cannot handle it, and parses the remainder of the source after the innermost heredoc to be one long interpolated string (edit: according to a person on the php dev team, this is fixed in 5.5).
I hope these oddities have been as amusing for you to read about here as they have been for me to discover.

Wednesday 5 June 2013
Facebook StumbleUpon Twitter Google+ Pin It

Making Google’s CalDAV and CardDAV APIs available for everyone

Author PhotoBy Piotr Stanczyk, Tech Lead

In March we announced that CalDAV, an open standard for accessing calendar data across the web, would become a partner-only API because it appeared that almost all the API usage was driven by a few large developers. Since that announcement, we received many requests for access to CalDAV, giving us a better understanding of developers’ use cases and causing us to revisit that decision. In response to those requests, we are keeping the CalDAV API public. And in the spirit of openness, today we’re also making CardDAV – an open standard for accessing contact information across the web – available to everyone for the first time.

Both of these APIs are getting other updates as well:
In addition, the CalDAV API now has a new endpoint:
https://apidata.googleusercontent.com/caldav/v2


Piotr Stanczyk is the Tech Lead of the Google Calendar APIs group. His current focus is to provide next generation Calendar APIs which make developers’ lives easier. He also participates in CalConnect consortium.

Posted by Scott Knaster, Editor


Tuesday 4 June 2013
Facebook StumbleUpon Twitter Google+ Pin It

Hacking for change at Google

Author PictureBy Patrick Copeland, Google.org

Cross-posted with the Google.org Blog

On June 1st and 2nd, thousands of developers from across the U.S. came together at nearly 100 different locations to participate in the first ever National Day of Civic Hacking. Using public data recently released by the government on topics like crime, health and the environment, developers built new applications that help address social challenges.


At the Googleplex in Mountain View, we hosted nearly 100 developers, statisticians, data scientists, and designers, who stayed long into the night hacking together prototypes that show how data on health and the environment can be used to enrich lives. Fusion Tables and Google App Engine were used to prototype, and groups relied on BigQuery as a workhorse to crunch the biggest datasets. Participants used Google+ Hangouts to connect with hackathons in other states and collaborated with Google Apps and platforms.

Here are a few highlights from the hackathon that stood out as useful, visually stunning, and informative ways to use public data:
  • Eat Healthy for Less, the winner of our Mountain View hackathon, is a mobile web application that uses the Consumer Pricing Index to suggest healthy recipes that can be made on a budget.
  • Data+, a reimagining of how we access data, can make exploring public datasets more intuitive and easily understandable for everyone.
  • Detoxic.org is a web experience and Android app that shows you toxic sites and landfills nearby that you might not know about so that you can take civic action against toxic waste.
Many of the ideas have great potential, and we are encouraging participants to continue their work. We hope that the National Day of Civic Hacking will be a catalyst for innovation in this space, and encourage you to keep track of our tools for civic developers at g.co/civicdevelopers.


Congratulations and thanks to everyone who participated!


Patrick Copeland is director of engineering at Google.org, where he works to build systems that leverage Google's reach to help people around the world.

Posted by Scott Knaster, Editor

A classic boardwalk game rolls from your phone to your computer—using only your browser

Author PhotoBy Pete LePage, Developer Advocate and Boardwalk King

Cross-posted from the Chromium Blog

Last week we launched Roll It, a Chrome Experiment that links phones to computers and gets people out of their chairs and swinging. We wanted to share how we built a physical game experience with no dedicated hardware. It requires just the web, your computer and a phone.

Here’s a look at the APIs and browser-based features we used to create it.


Roll It is a three-dimensional (3D) experience, from the swing of your phone’s accelerometer right up to the virtual models rendered on your computer’s HTML5 Canvas. On the phone side, we hooked into browser events like DeviceOrientation and DeviceMotion to detect the speed and direction of a swing. On the computer side we rendered our scene using Three.js and plugged in Physijs to add physics to the ball and environment.

To sync the phone to the computer we employed WebSockets which enable rapid two-way communication between devices via a central server.

For extra stability we built our backend on Google Cloud Platform:
We couldn’t have brought this experiment to life without a great team. The theme for Roll It was composed by Mr. Tim Healey. Legwork Studio developed the interfaces and game environment, and teamed up with Mode Set for the development.

To dig deeper into the technology behind Roll It, check out the HTML5 Rocks Case Study, or join the team for a Google Developers Live event this Friday, June 7, 2013 at 5pm GMT for an in-depth discussion.


Pete LePage is a Developer Advocate on the Google Chrome team and helps developers create great web applications and mobile web experiences.

Posted by Scott Knaster, Editor

Monday 3 June 2013
Facebook StumbleUpon Twitter Google+ Pin It

What is Object Oriented Programming (OOP)?

Introduction

Quite often I see a question in a newsgroup or forum along the lines of: What is this thing called ‘OOP’? What is so special about it? Why should I use it? How do I use it?. The person asking this type of question usually has experience of non-OO programming and wants to know the benefits of making the switch. Unfortunately most of the replies I have seen have been long on words but short on substance, full of airy-fairy, wishy-washy, meaningless phrases which are absolutely no use at all to man or beast.
Having created 1000′s of programs using non-OO languages, and another 500+ using the OO features of PHP I feel more than qualified to add my own contribution to the melting pot. According to some OO ‘purists’ I am not qualified at all as I was not taught to do things ‘their’ way and I refuse to follow ‘their’ methods. My response to that accusation is that there is no such thing as ‘only one true way’ with OOP just as there is no such thing as ‘only one true way’ with religion. People tell me that my methods are wrong, but they are making a classic mistake. My methods cannot be wrong for the simple reason that they work, and anybody with more than two brain cells to rub together will tell you that something that works cannot be wrong just as something that does not work cannot be right. My methods are not wrong, they are simply different, and sometimes it is a willingness to adopt a different approach that separates the code monkeys from the engineers.
One reason why some people give totally useless answers is that it was what they were taught, and they do not have the intelligence to look beyond what they were taught. Another reason is that some of the explanations about OO are rather vague and can be interpreted in several ways, and if something is open to interpretation it is also open to a great deal of mis-interpretation. If you do not believe that there is widespread confusion as to what OO is and is not then take a look at Nobody Agrees On What OO Is. Even some of the basic terminology can mean different things to different people, as explained in Abstraction, Encapsulation, and Information Hiding. If these people cannot agree on the basic concepts of OOP, then how can they possibly agree on how those concepts may be implemented.

What OOP is NOT

As a first step I shall debunk some of the answers that I have seen. In compiling the following list I picked out those descriptions which are not actually unique to OOP as those features which already exist in non-OO languages cannot be used to differentiate between the two.

OOP is about modeling the ‘real world’

OOP is a programming paradigm that uses abstraction to create models based on the real world. It provides for better modeling of the real world by providing a much needed improvement in domain analysis and then integration with system design.
Rubbish. OOP is no better at modeling the real world than any other method. Every computer program which seeks to replace a manual process is based on a conceptual software model of that process, and if the model is wrong then the software will also be wrong. The conceptual model is created as an analyst’s view of the real world, and the computer software is based solely on this conceptual model. OOP does not guarantee that the model will be better, just that the implementation of that model will be different.
The term "abstraction" is also open to interpretation, and therefore mis-interpretation, as discussed inUnderstand what "abstraction" really means. This is why some people’s abstractions look more like the work of Picasso when what is required should look like the work of Michelangelo.
That is why it is possible to create software that does A, B and C but it is useless to the customer as it does not also do X, Y and Z. The real world may contain X, Y and Z but the analyst did not include it in his model either because he did not spot it or because the customer failed to mention it in his Specification Of Requirements (SOR). I know because I have encountered both situations in my long career.
Not everyone agrees that direct real-world mapping is facilitated by OOP, or is even a worthy goal; Bertrand Meyer argues in Object-Oriented Software Construction that a program is not a model of the world but a model of a model of some part of the world; "Reality is a cousin twice removed".

OOP is about code re-use

The power of object-oriented systems lies in their promise of code reuse which will increase productivity, reduce costs and improve software quality.
Rubbish. This implies that code re-use is possible in OOP and not possible in non-OOP. Using OOP does not guarantee that more reusable code will be available as reusability depends on how the code is written, not the language in which it was written. It is possible to produce libraries of reusable modules in any non-OO language (I know, because I was doing just that with COBOL in 1985) just as it is possible to produce volumes of non-reusable code in any OO language.
It does not matter on the capabilities of the language as it is possible to have the same block of code duplicated in 100 places in any language. It is also possible, in any language, to put that block of code into a reusable module and call that module from those 100 places.
One of the early promises of OOP that I heard many years ago was that it would be possible for a software vendor to produce a library of pre-written classes, and for other developers to use these "off the shelf" classes instead of creating their own custom versions and thus "re-inventing the wheel". This dream never materialised, which just goes to prove that OOP promises much but delivers little.

OOP is about modularity

The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.
Rubbish. The concept of modular programming has existed in non-OO languages for many years, so this argument cannot be used to explain why OO is supposed to be better than non-OO. Just as it is possible in any language to hold the source code for an entire application in a single file, it is just as possible, in any language, to break that source code into smaller modules so that the source code for each module can be maintained and compiled independently of all other modules.

OOP is about plugability

If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.
Rubbish. This is the same as modularity where the source code for any individual module can be modified, recompiled and inserted into the application without having to touch any of the other modules.

OOP is about information hiding

By interacting only with an object’s methods, the details of its internal implementation remain hidden from the outside world.
Rubbish. In the first place OO is not about information hiding, it is about implementation hiding. In other words it is the code behind the API which is hidden from view. It is possible to use getters and setters to access the data, but even this is considered to be evil in some circles.
In the second place implementation hiding was never one of the aims of OOP, it is merely a by-product of encapsulation. The outside world can see the method names which can be used on a object, but not the code which exists behind those method names.
In the third place implementation hiding is not unique to OOP as I can distinctly remember in the 1980s writing applications in COBOL which interfaced with a commercial accounting package. The vendor of this package supplied us with a series of pre-compiled subroutines which we could call from our own code. We never saw the source code to any of these subroutines, we merely had a list of APIs and a description of what each API required as input and returned as output. How’s that for implementation hiding?

OOP is about the passing of messages.

Message passing is the process by which an object sends data to another object or asks the other object to invoke a method.
Rubbish. The way that an object’s method is invoked in an OO language is identical to the way in which a function or procedure in a non-OO language is invoked. If the language supports both non-OO functions and object methods (as PHP does) the method of invocation is called "calling", not "message passing". In fact in some languages it is necessary to specify the word "call" when invoking a subroutine.
non-OO: $result = function(arg1, arg2, ...)
OO:     $result = $object->function(arg1, arg2, ...)
The result of each invocation is exactly the same – the caller is suspended while control is passed to the callee, and control is not returned to the caller until the callee has finished.
I have worked with messaging software in the past and I can tell you quite categorically that they are completely different:
  • In the first place they allow messages to be passed from one process to another, not one module to another in the same process. The only exception I have seen to this was in a language which supported the creation of non-modal forms in which it was possible for one non-modal form to send a message to another non-modal form within the same application instance.
  • In the second place their behaviour is totally different:

    • They are are asynchronous, which means that after the caller drops a message into the message queue the caller can continue processing and does not have to wait until the callee returns control. E-mail is a classic example of such a messaging system.
    • The message queue may be able to contain any number of messages from any number of processes, and the receiving process picks out one message from the front of the queue, processes it, then looks for the next message.
    • The message may signify that an acknowledgement be sent back to the caller as soon as it has been received, or it may require a more elaborate result set to be returned after it has been processed.
    • In either case the message originator must contain the necessary code to deal with the acknowledgement and/or the result, which is in addition to the code which sends the message.
As you can see the mechanics of activating a method in an object is exactly the same as activating a non-OO function and nothing like passing a message in a messaging system.

OOP is about separation of responsibilities.

Each object can be viewed as an independent little machine with a distinct role or responsibility.
Rubbish. It depends entirely on how the module was written, and not the language in which it was written. It is possible to write independent modules in a procedural language such as COBOL, just as it is possible to write non-independent modules in an OO language.
The problem with "separation of responsibilities" is that different people have a different interpretation as to what it actually means. To some people the database operations such as SELECT, INSERT, UPDATE and DELETE require their own objects whereas others put them all together in a single data access object (DAO). Some programmers may have a separate DAO for each table in the database while others may have a single DAO which can deal with any and all database tables. Before you can separate any responsibilities you must first identify what those responsibilities are, and this is a design decision which is totally separate from the language in which the design is ultimately implemented.
In all my many years of experience the only project that I have ever been involved in which failed to be implemented due to "technical difficulties" was one where the system architects were OO "experts" who knew everything about this "separation of responsibilities". They designed a system around design patterns which had a different module for each responsibility which resulted in at least ten layers of code between the user and the database. This made the creation of new components far more complicated and convoluted than it need be, and it made testing and debugging an absolute nightmare. The result was far too expensive for the client, both in time and money, so he pulled the plug on the whole project and cut his losses. A pair of components which took 10 days to build using these "new fangled" OO techniques took me less than an hour to build using my "old fashioned" non-OO methods. So much for the superiority of OO.

OOP is easier to learn.

OOP is easier to learn for those new to computer programming than previous approaches, and its approach is often simpler to develop and to maintain, lending itself to more direct analysis, coding, and understanding of complex situations and procedures than other programming methods.
Rubbish. This is just marketing hype. Every new language/tool/paradigm is supposed to be better than everything else, but it rarely is. It is not what you use but how you use it that counts, and I have personally witnessed where an "old" language, when used by competent programmers, regularly out performed a "new" language which was advertised as being more productive by several orders of magnitude.
A person’s ability to learn something is often limited by the quality of the teachers or teaching materials, and I’m afraid that too much of what is being taught is too complicated, too inefficient, and more likely to lead to project failures than successes. Too often the teachers insist that there is "only one way" to do OOP, and that is where I most strongly disagree. I have successfully migrated to OOP by ignoring all these so-called experts and drawing on my years of experience with non-OO languages.


As you can see, the above descriptions are either too vague or not specific to OOP, so they cannot be used as distinguishing features.

What is an Object Oriented language?

A computer language can be aid to be Object Oriented if it provides support for the following:
ClassA class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind.
ObjectAn instance of a class. A class must be instantiated into an object before it can be used in the software. More than one instance of the same class can be in existence at any one time.
EncapsulationThe act of placing data and the operations that perform on that data in the same class. The class then becomes the ‘capsule’ or container for the data and operations.
InheritanceThe reuse of base classes (superclasses) to form derived classes (subclasses). Methods and properties defined in the superclass are automatically shared by any subclass.
PolymorphismSame interface, different implementation. The ability to substitute one class for another. This means that different classes may contain the same method names, but the result which is returned by each method will be different as the code behind each method (the implementation) is different in each class.
A class defines (encapsulates) both the properties (data) of an entity and the methods (functions) which may act upon those properties. Neither properties or methods which can be applied to that entity should exist outside of that class definition.

What OOP is

This is a lot simpler than some people would like you to believe. They like to use the more complicated definitions because it makes them sound more intelligent than they really are. Here is the real definition:
Object Oriented Programming is programming which is oriented around objects, thus taking advantage of Encapsulation, Polymorphism, and Inheritance to increase code reuse and decrease code maintenance.

The difference between OOP and non-OOP

A better way of trying to explain the differences between non-OO and OO programming is to actual examples.

They are defined differently

A function is defined as a self-contained block of code. Each function name "fName" must be unique within the application.
function fName ($arg1, $arg2) 
// function description
{
    ....
    
    return $result;

    
} // fName
A class method is defined within the boundaries of a class definition. Each class name "cName" must be unique within the application. Each class may contain any number of functions (also known as "methods"), and the function name "fName" must be unique within the class but need not be unique within the application.
class cName
{
    function fName ($arg1, $arg2) 
    // function description
    {
        ....
        
        return $result;
        
    } // fName
    
} // cName

They are accessed differently

It is important to note that neither a function nor a class can be accessed until the function/class definition has been loaded.
Calling a function is very straightforward:
$result = fName($arg1, $arg2);
Calling a class method is not so straightforward. First it is necessary to create an instance of the class (an object), then to access the function (method) name through the object. The object name must be unique within the application.
$object = new cName; 
$result = $object->fName($arg1, $arg2);

They have different numbers of working copies

A function does not have to be instantiated before it can be accessed, therefore only one copy (or instance) is said to exist at any one time.
A class method can only be accessed after it has been instantiated into an object, and it is possible to create multiple instances (objects) of the same class with different object names.
$object1 = new cName;
$object2 = new cName;
$object3 = new cName; 

They have different numbers of entry points

A function has only a single point of entry, and that is the function name itself.
An object has multiple points of entry, one for each method name.

They have different methods of maintaining state

A function by default does not have state, by which I mean that each

time that it is called it is treated as a fresh invocation and not a continuation of any previous invocation.
An object does have state, by which I mean that each time an object’s method is called it acts upon the object’s state as it was after the previous method call.
It is possible for both a function and a class method to use local variables, and they both operate in the same way. This means that the local variables do not exist outside the scope of the function or class method, and any values placed in them do not persist between invocations.
It is possible for a function to remember values between different invocations by declaring a variable as static, as in the following example:
function count () {
    static $count = 0;
    $count++;
    return $count;
}
Each time this function is called it will return a value that is one greater than the previous call. Without the keyword static it would always return the value ’1′.
Class variables which need to persist outside of a function (method) are declared at class level, as follows:
class calculator
{
    // define class properties (member variables)
    var $value;
    
    // define class methods
    function setValue ($value) 
    {
        $this->value = $value;
        
        return;
        
    } // setValue
    
    function getValue () 
    // function description
    {
        return $this->value;
        
    } // setValue
    
    function add ($value) 
    // function description
    {
        $this->value = $this->value + $value;
        
        return $this->value;
        
    } // setValue
    
    function subtract ($value) 
    // function description
    {
        $this->value = $this->value - $value;
        
        return $this->value;
        
    } // setValue
    
} // cName
Note that all class/object variables are referenced with the prefix $this-> as in $this->varname. Any variable which is referenced without this keyword, as in $varname, is treated as a local variable.
Note also that each instance of the class (object) maintains its own set of variables, so the contents of one object are totally independent of the contents of another object, even it is from the same class.

Practical Examples

Here are some practical examples which demonstrate Encapsulation, Inheritance and Polymorphism.

Encapsulation

EncapsulationThe act of placing data and the operations that perform on that data in the same class. The class then becomes the ‘capsule’ or container for the data and operations.
Every application deals with a number of different entities or "things", such as "customer" "product" and "invoice", so it is common practice to create a different class for each of these entities. At runtime the software will create one or more objects from each class definition, and when it wants to do something with one of these entities it will do so by calling the relevant method on the relevant object.
The data held within each object at runtime cannot remain in memory for ever, so it is written out to a persistent data store (a database) with a separate table for each entity. There are only four basic operations which can be performed on a database table (Create, Read, Update, Delete) so I shall start by creating a method for each one.
class entity1
{
    // class properties
    var $dbname;           // database name
    var $errors = array(); // array of error messages, indexed by field name          
    var $fieldarray;       // associative array of name=value pairs
    var $fieldspec;        // array of field specifications
    var $numrows;          // number of database rows affected
    var $primary_key;      // array of field names which make up the primary key
    var $tablename;        // table name
    
    // class methods
    function entity1 ()
    // constructor
    {
        $this->tablename   = 'entity1';
        $this->dbname      = 'foobar';
        
        $this->fieldlist   = array('column1', 'column2', 'column3', 'column4');
        $this->primary_key = array('column1');
        
    } // entity1
    
    // class methods
    function getData ($where)
    // read data from the database which satisfies the selection criteria in $where
    {
        ....
        
        return $this->fieldarray;
        
    } // getData
    
    function insertRecord ($fieldarray)
    // create a database record using the contents of $fieldarray
    {
        ....
        
        return $this->fieldarray;
        
    } // insertRecord
    
    function updateRecord ($fieldarray)
    // update a database record using the contents of $fieldarray
    {
        ....
        
        return $this->fieldarray;
        
    } // updateRecord
    
    function deleteRecord ($fieldarray)
    // delete a database record identified in $fieldarray
    {
        ....
        
        return $this->fieldarray;
        
    } // deleteRecord
    
} // entity1
Please note the following:
  • The class constructor identifies the physical characteristics of this database table, that which makes it unique from all other database tables. The contents of the class constructor are performed automatically when the class is instantiated into an object.
  • All the table data is held in a single array of fields rather than a separate variable for each field. For a detailed explanation as to why I choose this method please read Why don’t you use GETTERS and SETTERS?
  • I have not bothered including the actual code within each method as it there is too much of it. It you really want to see the code that I use then you can download it, either for my small sample application, or my full development framework.
  • There are actually many more methods than the four mentioned, but these are enough to begin with.
Each of these classes therefore acts as a ‘capsule’ which contains

both the data for an entity and the operations which can be performed

upon that data. This is ‘encapsulation’.

Inheritance

InheritanceThe reuse of base classes (superclasses) to form derived classes (subclasses). Methods and properties defined in the superclass are automatically shared by any subclass.
After writing and testing a class to deal with ‘entity1′ I copied it and made it work for ‘entity2′. I then compared the two classes to see what code was common and could be shared, and what code was unique and could not be shared. I then transferred all the common code into a separate class known as a ‘superclass’.
Firstly, to create the superclass, I changed the class name and the constructor to the following:
class default
{
    // class properties
    ....
    
    // class methods
    function default ()
    // constructor
    {
        $this->tablename   = 'unknown';
        $this->dbname      = 'unknown';
        
        $this->fieldlist   = array();
        $this->primary_key = array();
        
    } // default
    
    // class methods
    function getData ($where)
    
    ....
    
    function insertRecord ($fieldarray)
    
    ....
    
    function updateRecord ($fieldarray)
    
    ....
    
    function deleteRecord ($fieldarray)
    
    ....
    
} // default
This class cannot be used to instantiate a working object as it does not refer to a database table which actually exists, so it is what is known as an ‘abstract’ class.
Secondly, I altered each table class to remove the common methods and properties, and included the keyword extends to force inheritance from the superclass.
include 'default.class.inc';
class entity1 extends default
{
    function entity1 ()
    // constructor
    {
        $this->tablename   = 'entity1';
        $this->dbname      = 'foobar';
        
        $this->fieldlist   = array('column1', 'column2', 'column3', 'column4');
        $this->primary_key = array('column1');
        
    } // entity1
    
} // entity1
When a subclass is instantiated into an object that object will contain all the properties and methods of the superclass as well as those of the subclass. If anything has been defined in both the superclass and the subclass, then the definition from the subclass will be used.
In my current development environment the superclass contains several thousand lines of code, but there is only one copy of this code which is inherited by several dozen table classes. Inheritance is therefore a powerful mechanism for making one copy of common code accessible to many objects instead of having multiple copies of that common code.

Polymorphism

PolymorphismSame interface, different implementation. The ability to substitute one class for another. This means that different classes may contain the same method names, but the result which is returned by each method will be different as the code behind each method (the implementation) is different in each class.
Polymorphism can only be employed where the same method names exist in several classes. This means that the same method can be used on different objects, but will yield different results as the implementation of that method is different within each class.
For example, take a series of classes called ‘Customer’, ‘Product’ and ‘Invoice’. One practice I have seen which makes polymorphism impossible is to incorporate the entity name into the method name, as in:
  1. getCustomer(), insertCustomer(), updateCustomer() deleteCustomer()
  2. getProduct(), insertProduct(), updateProduct() deleteProduct()
  3. getInvoice(), insertInvoice(), updateInvoice() deleteInvoice()
The problem with this approach is that the object (the controller in MVC) which communicates with each table object (the model in MVC)needs to know the method name before it can open up that channel of communication. If each model has a unique set of method names then it must have a unique set of controllers to communicate with it.
My approach is to use a standard set of method names for standard operations, as in:
  1. getData(), insertRecord(), updateRecord() deleteRecord()
This is made easier as these methods are defined in the superclass and made available to each subclass through inheritance.
The advantage of this is that I can have one standard controller for each standard function, and this controller can work with any table class in the system. This is far better than having a separate set of controllers for each table class.
Here is some example code from one of my controllers:
....
include "$table.class.inc";
$object = new $table;
$data = $object->getData($where);
....
The contents of $table and $where are made available at runtime.
The significant point is that the name of the class (database table) is not hard-coded into the controller, it is passed as an argument at runtime. Only the method names are hard-coded, but as these method names exist within every table class by being inherited from the superclass they will always work. So, if the class name is ‘Customer’ the controller will obtain data from the ‘Customer’ table, if it is ‘Product’ it will obtain data from the ‘Product’ table, and so on.

Conclusion

Many people use different words to describe what OOP is supposed to mean, but the problem with words is that they are slippery. Like Humpty Dumpty proclaimed in Lewis Carroll’s Through the Looking Glass:
When I use a word, it means just what I choose it to mean — neither more nor less.
If you take the words used by the originators of OOP and apply different meanings to those words, then others take your words and apply different meanings to them, then you can end up with something which is nothing like the original, as immortalised in that children’s game called Chinese Whispers.
There are only three features which really differentiate an Object Oriented language from a non-OO language, and these are Encapsulation, Inheritance and Polymorphism. Everything else is either bullshit or hype. Object Oriented Programming is therefore the use of these features in a programming language. High reusability and low maintainability cannot be guaranteed – that depends entirely on how these features are implemented.
Some people accuse me of having a view of OOP which is too simplistic, but instead of saying that my view is "more simple than it need be" surely it can also mean that their view is "more complex than it need be"? As a long-time follower of the KISS principle I know which view I prefer, and I also know which view is easier to teach to others.

Sunday 2 June 2013
Facebook StumbleUpon Twitter Google+ Pin It

Ajax PHP Database Operation

Ajax PHP database operation



Hi, In this tutorial you’re going to find out ajax php database operation i.e. how to show list of values from db using ajax via php
When a user selects a Name in the dropdown list below, a function called “showDetails()” is executed. The function is triggered by the “onchange” event :
In the above code we are passing value of the option to the function showDetains() onChange

Ajax Source

Ajax function receives the value and checks whether it is an empty value if it is an empty value it returns blank otherwise it sends the value to results.php with GET method and then it will receive the output given from results.php and shows it in the results div area

PHP source

results.php gets the value and using mysql query the results have been extracted from the db
-By Parthiv Patel
Parthiv Patel
Bhaishri Info Solution
Sr. PHP Developer
Limdi Chowk, AT PO. Nar, Di. Anand
Nar, Gujarat
388150
India
pparthiv2412@gmail.com
7383343029
DOB: 12/24/1986