Thursday, November 27, 2014

Intro with PHP example

I've been studying design patterns for some time and one thing I've found is that despite the fact that web design is very different from C++ programming the exact same design patterns are being used for both.   This is fine but each language has idiosyncrasies that I believe should vastly alter and expand the number of design patterns possible.     I mean when you program a C++ program you are only using one language but web programming combines languages.  When you combine languages then the way you combine them becomes much more important a design factor and of course when using one language this factor doesn't exist.    Another example would be PHP.  Since you call PHP from other PHP files then wouldn't the way you call other files be an important factor?   Should you only call other files at the top of a script or is it fine to call them from anywhere in the script.   Should you be allowed to use variables created in one script from the calling script?   I would say no since that goes against the rules of even structural programming.  Many times though this it what people do.  I constantly come across PHP files where scripts are called from arbitrary locations in other scripts.   When this happens though it's hard to tell what is being done.

Essentially this boils down to treating whole pages as if they were functions:
 <?php
$x = 4;  //initializing variables outside the called script is some help in making a script a function but
$y = 5; // often this step isn't taken and add would itself contain the variables
include("add.php")
echo $z;
?>
This would output 9.     As silly as this may seem this is what people actually do.  It's very terse though but not very clear.   Another pattern would be to do this:

<?php
include("add.php");

echo add(4, 5);
?>

This would also output 9.


Another possible pattern is this:
<?php
function add($x, $y){
     return $x + $y;
}

include("output.php");
?>

You could then create a file called output.php and then in your output file you would not need to include anything except the function add(4,5);
<?php
echo add(4,5);
?>

All these are different patterns.  The purpose of this blog is more to open peoples eyes to the fact that the term Design Pattern is being used in a much too narrow way.

No comments:

Post a Comment