Updating Legacy Code
Dave Widmer
Web Applications Developer: BGSU
@davewidmer
Web Applications Developer: BGSU
@davewidmer
Back To Basics
What is a Class?
Basic class definitions begin with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class.
The class name can be any valid label which is a not a PHP reserved word. A valid class name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.
A class may contain its own constants, variables (called "properties"), and functions (called "methods").
<?php
$var = 'a default value';
function displayVar($var) {
echo $var;
}
<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
}
}
$this
Creating a "new" Instance
<?php
$instance = new SimpleClass();
$instance->displayVar(); // Outputs 'a default variable'
Extending
<?php
class ExtendClass extends SimpleClass
{
// Redefine the parent method
public function displayVar()
{
echo "Extending class\n";
parent::displayVar();
}
}
<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
}
}
$extended = new ExtendClass();
$extended->displayVar();
Output?
Public, Protected, Private
Visibility
<?php
class MyClass
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';
public function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected;// Fatal Error
echo $obj->private; // Fatal Error
What about $obj->printHello()?
How about extended printHello()?
Updating Legacy Code???
The Indecisive Beer Drinker
if ( ! function_exists('random_beer'))
{
function random_beer()
{
$beers = array(
'Guiness',
'Sam Adams',
'Bells'
);
$key = array_rand($beers, 1);
return $beers[$key];
}
}
Where do you keep this?
How do you find it again?
BeerHelper.php to the Rescue!
if ( ! function_exists('random_beer'))
{
function random_beer()
{
$beers = array(
'Guiness',
'Sam Adams',
'Bells'
);
$key = array_rand($beers, 1);
return $beers[$key];
}
}
=>
<?php
class BeerHelper
{
public static function random()
{
$beers = array(
'Guiness',
'Sam Adams',
'Bells'
);
$key = array_rand($beers, 1);
return $beers[$key];
}
}
Use
include "BeerHelper.php";
$giveMeA = BeerHelper::random();
Examples
Format
class Format
{
public static function phone($num)
{
$clean = preg_replace("/\D/", "", $num);
$area = substr($clean, 0, 3);
$city = substr($clean, 3, 3);
$local = substr($clean, 6, 4);
return "(".$area.") ".$city."-".$local;
}
public static function date($date, $format = "F jS, Y")
{
$date = \DateTime::createFromFormat("Y-m-d", $date);
return $date->format($format);
}
}
Use
Format::phone(1234567890); // "(123) 456-7890"
Format::phone("123asdf456ggasdf7890"); // "(123) 456-7890"
Format::date('2012-08-21'); // "August 21st, 2012"
Database Interaction
Databases: The Functional Way
$con = mysql_connect("localhost", "root", "") or die('Could not connect: ' . mysql_error());
mysql_select_db("accordion", $con) or die('Could not open database: ' . mysql_error());
$result = mysql_query("SELECT id, text, URL FROM topics ORDER BY ordering") or die('Error: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)):
// Display the results to the screen
endwhile;
mysql_close($con);
You copy this into every page?
Let's Code A Database Class
My Class
class Database_MySQL
{
protected $connection = null;
public function __construct(array $config)
{
$this->connection = mysql_connect($config['host'], $config['user'], $config['password']) or die('error...');
mysql_select_db($config['database', $this->connection]) or die('error....');
}
public function query($sql)
{
$result = mysql_query($sql); // Make sure your queries are safe!!!!!!!!!
$resultSet = array();
while($row = mysql_fetch_assoc($result))
{
$resultSet[] = $row;
}
return $resultSet;
}
public function __destruct()
{
if ($this->connection !== null)
{
mysql_close($this->connection);
}
}
}
On Your Own
- Constructors and Destructors
- Magic Methods
- Autoloading
- Abstraction
- Interfaces
- Exceptions
- Namespaces (5.3+)
- Traits (5.4+)
Resources
Function Spotlight
array_map
array_map
Applies the callback to the elements of the given arrays
array array_map ( callable $callback , array $arr1 [, array $... ] )
Example
$beers = array('guiness', 'sam adams', 'bells');
$capitalized = array_map('ucwords', $beers);
array(3) {
[0]=> string(7) "Guiness"
[1]=> string(9) "Sam Adams"
[2]=> string(5) "Bells"
}