My Advanced PHP Reference

much information gathered from:

Ullman, Larry (2012-09-13). PHP Advanced and Object-Oriented Programming: Visual QuickPro Guide (3rd Edition) (p. ix). Pearson Education (US). Kindle Edition.

Chapter Term Meaning Syntax Usage Notes Real World ex
4 object instance of a class $object = new className;    
4 attribute variable

accesstype $var

but must include public (default if not specified), protected, or private (then convention says precede _varname with underscore).

property or attribute.

These must be declared as private public or protected and if initialized, must be given a static value (not expression based). They appear in new instances of the object without the var symbol($).

The $this->attribute inside a class definition always refers to the current instance (i.e., the object involved) of that class.

for $this: say class Bikes, having attribute defined $model, would be referred to as $this->model inside the class and outside after object say, $bike, creation, $bike->model

 

4 method function

function functionName(){}

 

 

verb

You can over-ride methods by declaring the same method with same arguments.

You can prevent over-riding of methods by declaring it "final"; in a parent class. Trying to override a final function in a child class generates a fatal error.

There is a concept called overloading - which could allow more arguments than the original method.

A function's name and arguments is called "signature".

 
4 class a group of abstracted things and actions - consider it like a recipe to make something, with the object being food made from that recipe. class className{}

No direct correlate in procedurual- one could argue an include file often performs this role - but not in a defined or heirarchical manner.

(from ch6 page 209): A well-designed class or method can have its implementation changed without affecting any code that uses the class, as the interface should remain unchanged.
Similarly, classes, even in a complex application, should be loosely coupled. This means that classes should be written so they are not too strongly dependent on the design or functionality of another class.

 

 

 

create parts of a bigger whole for easier flexible assembly

 

4 constructor   function __contruct(){}

constructor: a special method using the convention syntax __contructor(){}, that will define things that should always be done upon a new instance of an object.

(from ch6) be in the habit of using constructors that guarantee the generated object is in a safe state to be used. This means initializing internal attributes and performing any necessary setup.

 
4 $this   $this->attribute

The issue is that within the class itself (i.e., within a class’s methods), you must use an alternative syntax to access the class’s attributes. The solution is a special variable called $this. The $this variable in a class always refers to the current instance (i.e., the object involved) of that class. Within a method, you can refer to the instance of a class and its attributes by using the $ this->attributeName syntax.

 

 
5 static a value that is shared between instances of a class. static methodName or $attribute    
5 access control   public, private, protected

Access Control:(think of concentric circles)

public: (the default if undeclared): any page/script/class where the class is present.

protected: the class and derived override classes

private: only the class declared within

If a class has a method that should only ever be called by the class itself, it should also be marked either protected or private.

 
6 Abstract Classes A "base" that is not called, but rather extended. Creates a template for child classes. abstract class Classname{} Can have non-abstract members.  
6 Abstract method abstract defined functions in an abstract class

abstract function methodName(opt $var1, opt $var2)

- but the methodology is not defined, it is defined in the extension class(es).

if an abstract function is public, the extended version must also be public. (must follow the weakest visibility).

Having one abstract method requires and abstract class. However, an abstract class can have non-abstract methods, as well as attributes, all of which would also be inherited by the derived class.

? what are the real benefits?

 

 
6 interface identify methods that must be defined by a specific class

interface iSomething {    

public function someFunction( $ var);

}

define the signatures, not implementation

convention says begin interface name with lowercase i, thus isomeInterface{}

to associate a class with an interface, use implement, thus:

class SomeClass implements iSomething{}

all methods must be public in an interface

only include methods, never attributes

if class implementing an interface does not define all the methods of an interface, a fatal error will occur.

Another benefit that interfaces have over using abstract classes and inheritance is that classes in PHP cannot inherit from multiple parents. Classes, however, can implement multiple interfaces by separating each by a comma:

http://php.net/manual/en/language.oop5.interfaces.php - has a great comment on the use of interfaces by user dlovell2001 at yahoo dot com

 
6 clone create copy of an object that is not referencing originals members clone <$object>    
6 traits

solves problem in OOP languages that only alow for single inheritance

 

to define:

trait tSomeTrait {  
 // Attributes    
function someFunction() {    
   // Do whatever.    }
}

to use:

class someClass{
use tSomeTrait;
//rest of class
}

traits allow adding of functionality to multiple classes without using inheritance

if there is a trait method the same in a trait as in the class using the trait, the class method wins. But, if it's inherited method, the trait will win.

the tdebug in ch6 is a good example of something pretty cool and useful.

 
6 composition indicates a relationship with another class value used in UML    
6 Type Hinting hint the object type by referring to an outside classname in a method

class SomeClass {

function doThis( OtherClass $var) {    }

}

Failing to access the referenced $var will generate an exception (catchable) error

Hinting a class will require the presence of an object of that class type and thus give access to its signature components.

Type hinting can be used in functions, too (i.e., in non-methods: functions defined outside of any class).

You can also hint for interfaces, arrays (as of PHP 5.1), and functions (i.e., callables, as of PHP 5.4).

 
6 Namespaces gives ability to separate similar names and classes into separate "safe" areas

//only comments before in a new file!
namespace myNameSpace;
<all your valid code for the namespace>

//or subnamespace(s):

namespace mySub\myNameSpace;

to use:


$ obj = new \SomeNameSpace\ SomeClass();

Or:

require(' MyUtilities\ User\ User.php');

$ obj = new \MyUtilities\ User\ Login();

 

note: backslashes!

best analogy is a file/folder structure - disallowing the same folder to have the same filename in it - but give it separate folders - and it's fine.

namespaces hold: classes, functions, constants, interfaces

Tip You can use the same namespace in multiple files, which will allow you to put multiple classes, each defined in separate scripts, within the same namespace.

Tip Technically, the namespace keyword can come after one particular line of PHP code: a declare() statement.

Tip You can define multiple namespaces within a single file, but I recommend against doing so.

Tip The __NAMESPACE__ constant represents the current namespace.

Tip PHP allows you to more quickly reference a namespace by bringing it into current scope via the use keyword: use MyNamespace\ Company; Having done that, you can now create an object by just referencing classes within the Company namespace: $ obj = new Department(); I tend to avoid these kinds of heavy-handed approaches, though, as the purpose of namespaces is to be specific.

Tip The PHP manual goes into a lot of detail about how namespaces are resolved considering various scopes. If you begin using namespaces on a regular basis, read through that section of the PHP manual.

 

 
7 Design Pattern Abstract programming approach that helps identify broad scope solutions. NA

Based on architecture.

Hardest thing is to decide which pattern applies to which situation.

The seminal programming book on the subject of design patterns is Design Patterns: Elements of Reusable Object-Oriented Software, by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Addison-Wesley Professional, 1994). You’ll see this group of authors referred to as the “Gang of Four,” abbreviated as GoF.

The Design Patterns book identified 23 patterns, organized into three broad categories: creational, structural, and behavioral. The book primarily uses C + + for its examples, along with Smalltalk, but the whole point of design patterns is that they define approaches, regardless of the language in use.

Creational patterns create objects, saving you from having to do so manually in your code. The Builder, Factory, Prototype, and Singleton patterns are all creational; Factory and Singleton are covered in this chapter.

Structural patterns assist in the creation and use of complex structures. Examples of structural patterns include Adapter, Bridge, Composite (covered in this chapter), Decorator, Façade, and Proxy.

Behavioral patterns address how objects within a system communicate and how a program’s logic flows. The Command, Iterator, Observer, State, Strategy (covered in this chapter), and Template Method patterns are all behavioral.

 
7 Singleton Pattern a design pattern where only one 'single' instance of an object will exist.

the trick is in the construct and definition;

static private $_instance=NULL;
private $_settings= array();

private function __construct(){}
private function __clone(){}

static function getInstance(){
if (self::getInstance == NULL){
self::getInstance()= new Config();
}
else {
return self::$_instance;
}
}

A "creation" pattern.

Convention sometimes gives Singleton vars all CAPS like a constant for its name. ie $CONFIG

Because the class’s constructor is private, you cannot use new to create an object of this type.

 

Database connector

 

7 Factory Pattern Create potentially multiple objects of many different class types.

static function Create($type) {
 // Validate $type.    
return new SomeClassType();
}

 

A creation pattern (like singleton).

The Factory pattern becomes useful in situations where the type of object that needs to be generated isn’t known when the program is written but only once the program is running. In very dynamic applications, this can often be the case.

Another clue for when the Factory pattern might be appropriate is when there’s an abstract base class, and different derived subclasses will need to be created on the fly. This particular design structure is important with the Factory pattern, as once you’ve created the object, regardless of its specific type, the use of that object will be consistent.

The Factory pattern works via a static method, conventionally named Create(), factory(), factoryMethod(), or createInstance(). The method takes at least one argument, which indicates the type of object to create. The method then returns an object of that type

The Factory pattern is also meant to be easily extendible (i.e., supporting new classes as they are defined).

Tip: One of the consequences of using the Factory pattern is that the Factory class is very tightly coupled with the rest of the application, due to its internal validation. You can see this in the ShapeFactory Create() method, which makes assumptions about the incoming $ sizes array.

Tip A variation on the Factory pattern is Abstract Factory. Whereas the Factory pattern outputs different objects, all derived from the same parent, the Abstract Factory outputs other factories.

 

 

 
7 Composite Pattern Suite or employed when some kind of heirarchy is present to extend some potential asbtract base class where you would like to do similar things to the various extensions.

type hinting.

abstract class FormComponent {     abstract function add (FormComponent $ obj);     abstract function remove (FormComponent $ obj);     abstract function display();     abstract function validate();     abstract function showError(); }

class Form extends FormComponent {     private $_elements = array();     function add( FormComponent $ obj) {         $ this->_elements[] = $ obj;    }     function display() {        // Display the entire form.    } } class FormElement extends FormComponent {     function add( FormComponent $ obj) {         return $ obj; // Or false.    }     function display() {        // Display the element.    } }

Thus, add elements to a form:

$form = new Form();

$email = new FormElement();

A structural pattern.

Analogy to tree>leaves. Abstract may define trunk, then leaves by extension.

The Composite pattern allows one class type to be used like another, even if one is composed of the other class type.

Tip: The Visitor pattern, which allows for operations across structures, is often used in conjunction with Composite.

Tip: This example could be extended so that teams could be made up of employees or other teams.

Tip: Another way of implementing this example using the Composite pattern would be to focus on the tasks. New tasks could be treated individually, or created as steps in other tasks. Then an individual task or a group of tasks could be assigned to work units.

Antipatterns: In learning about design patterns, you’ll often come across the term antipattern. A design pattern is a best practice; an antipattern is, therefore, an example of what we know did not work. As any developer comes to know, you learn as much, if not more, from your failures as from your successes.

 

 

 
7 Strategy Pattern The strategy pattern is designed to change an algorithm on the fly, versus the object type on the fly like a Factory/creation type.  

A behavioral pattern - ie how an application runs.

In the Strategy pattern, an interface is extended by more concrete classes, which in turn are used by a specific object (the Context).

Strategy is most useful in situations where you have classes that may be similar, but not related, and differ only in their specific behavior.

 

 

 

For example, say you need a filtering system for strings. Different filters might include: • Stripping out HTML • Crossing out swear words • Catching character combinations that can be used to send spam through contact forms and the like

 

8 Exception Class PHP's built in error handling class
/* Properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] )
final public string getMessage ( void )
final public Exception getPrevious ( void )
final public mixed getCode ( void )
final public string getFile ( void )
final public int getLine ( void )
final public array getTrace ( void )
final public string getTraceAsString ( void )
public string __toString ( void )
final private void __clone ( void )

 

To catch exceptions, make sure all object code is in the try block (ie, creation of object etc)

Note that only the Exception constructor and _ _toString() methods can be overridden, because the others are all defined as final.

Exception Class UML

 

 
8

try {

}

catch {

}

object error handling      
8 PDO PhpDataObjects Class

Shortest Syntax (not best practices)

$pdo = new PDO(dsn string, $username, $password)

to INSERT, UPDATE and DELETE,

$pdo->exec($query),

for SELECT statements:

$r = $pdo->query($q);

$rows = $r->fetchAll;

Note to make rowCount() work with SELECT, setup up pdo with:

array(PDO::MYSQL_ATTR_FOUND_ROWS => true)

You can change the level of database error reporting using the PDO setAttribute() method and the proper constants. See the PHP manual for details.

Tip If the query ran through the exec() method affects no records, the number 0 is returned. If the query generates an error, false is returned.

Tip The quote() method relies on the data-base’s default character set being established.

 

Warning from: http://www.php.net/manual/en/pdo.connections.php

If your application does not catch the exception thrown from the PDO constructor, the default action taken by the zend engine is to terminate the script and display a back trace. This back trace will likely reveal the full database connection details, including the username and password. It is your responsibility to catch this exception, either explicitly (via a catch statement) or implicitly via set_exception_handler().

 

 

 

 
8 Prepared Statements A more secure and faster method for making db queries.
  1. create $db (pdo database object) - usually in db definition area
  2. create a $query (string with ? or :arraykey
  3. have some $data to put into the statement
  4. create $stmt object to handle preparation and execution as follows:
  5. $stmt = $db->prepare($q)
  6. $stmt->execute($data)
  7. option bindings for selects

Prepared statements will have the largest performance benefits in scripts that execute the same query multiple times with only the data changing on each execution.

??Only best practice for INsert, UPdate and WHERE?

PDO also supports transactions, assuming that the database application does.

http://stackoverflow.com/questions/535464/when-not-to-use-prepared-statements - which has this: I think you want PDO::ATTR_EMULATE_PREPARES. That turns off native database prepared statements, but still allows query bindings to prevent sql injection and keep your sql tidy. From what I understand, PDO::MYSQL_ATTR_DIRECT_QUERY turns off query bindings completely.

http://php.net/manual/en/pdo.prepared-statements.php

 
8 Standard PHP libary (SPL) As of PHPv5, a collection of commonly used tools.  

Tip The SPL also implements many Gang of Four design patterns, such as Iterator and Observer.

Tip As of PHP 5.3, SPL cannot be disabled. This means that if you’re using PHP 5.3 or greater, you have support for SPL.

As of 5.4 - SessionHandlerInterface Class

 

 
8 File Handling with SPL SplFileInfo contains many methods for accessing file info

new SplFileInfo('file') allows these methods:

• getBasename()

• getExtension()

• getMTime()

• getPathname()

• getSize()

• getType()

• isDir()

• isFile()

isWritable()

   
8 File Object SplFileObject inherits SplFileInfo and adds read write to a file

new SplFileObject('file', 'mode')

fwrite()

fgets()

 

crazy cool and powerful.

http://www.php.net/manual/en/class.splfileobject.php

 
8 Iterators design pattern that makes it posible to access components of any kind of complex data structure using a loop.

DirectoryIterator

ArrayIterator

RecursiveArrayIterator

LimitIterator

RecursiveDirectoryIterator

 

http://php.net/manual/en/spl.iterators.php

The FilterIterator can be used with a DirectoryIterator to limit what kinds of files are iterated.

Tip The LimitIterator allows you to page through a list, similar to using a LIMIT clause in a SQL command.

Tip The SPL defines a couple of recursive iterators that make it easier to navigate nested lists (such as directories or multidimensional arrays).

 
8 SPL Data Structures used to create specific more limited variations on arrays SplFixedArray

php arrays potentially permit sloppier coding

Again, this is just a more restricted type of array, but restrictions are sometimes for the best. For example, if you have an array that stores a sequence of steps, you might only let the user go back a step, not to any random step. That kind of restriction can be enforced with a stack, but not a standard array.

 
8 AutoLoader auto load needed classes

spl_autoload_register (' class_loader');

function class_loader( $class) {   require( $class . '. php');}

 

http://www.php.net/manual/en/function.spl-autoload-register.php  
9 MVC archictecture for programming option na

MVC can be used for application design just as it can Web design. In a Web environment, the Models are normally represented by database tables, although some Models can also represent form data that doesn’t get stored in the database (such as that used in a contact form). Naturally, on a Web page, the Views are the HTML pages— the final, dynamically generated output— that the user actually sees. The Controllers react to user actions, such as the request of a single page or the submission of a form. Controllers implement the logic: validate some data, insert it into a database, show the results, and so forth.

 
9

serialize() function

 

will output a string that represents a complex data type

$form = new Quickform2('formname, ie login, add post etc')

 

 

Tip Better yet, you can have QuickForm2 perform not only server-side validation (using PHP) but also client-side (by generating the necessary JavaScript). See the QuickForm2 documentation for details. Tip You can create your own validation rules and then declare them for use by invoking registerRule(). This could be done, for example, to make sure that a username or email address has not already been registered. The function involved would check your database for that name or address’s presence. Again, see the QuickForm2 documentation for the specifics.

 

9 QuickForm2 Very cool Pear class for creating, validating and displaying HTML forms

establish pear connection and include

https://pear.php.net/manual/en/package.html.html-quickform2.elements.list.php

http://pear.php.net/package/HTML_QuickForm2/docs/latest/HTML_QuickForm2/HTML_QuickForm2_Controller_DefaultAction.html

Quickform Elements

added elements

Quickform_validate

 

 
10 fopen (external) open / read pages from other sites fopen('url/dir/page.ext')   http://www.gummy-stuff.org/Yahoo-data.htm
10 network url, ip and domain functions

parse_url():Separates a url into components:
$url = 'http://www.epiano.com/index.php?week=2';

Array  ([scheme] => http
[host] => www.epiano.com
[path] => /index.php
[query] => week=2 )

 

$url_pieces = parse_url($url);    
10 fsockopen() socket open like fopen, but better for remote address connection and other streaming type applications   http://en.wikipedia.org/wiki/Network_socket  
10 socket server A socket server is a service assigned to a particular port
that listens to incoming requests and responds to them.


Email servers (POP3, SMTP) and web servers are good examples
of socket servers. An HTTP (web) server listens on port 80 to incoming requests
and serves back HTML and other files (images, documents etc).



Socket Servers normally run continuously as a service or a daemon.

http://devzone.zend.com/209/writing-socket-servers-in-php/   Now that you know the basics of creating a socket server, the
only limitation is your imagination. Here are some ideas:


  • Chat server (using a text based or graphical interface). This can be for fun or real application
    (e.g. customer support representatives).
  • Real time information streaming (news, stocks etc.)
  • Streaming multimedia (images, videos and sounds)
  • Authentication server
  • Simple web, POP3, SMTP and FTP servers.

Furthermore, the sockets library can be used to
create client programs as well as servers.
10 geo ip locating use the freegeoip.net web site to get the location of an ip address.

URL should be in the format http:// freegeoip.net/{ data_format}/{ IP_address}.

 

   
10 curl client URLs - a big library of functionality for working with networks and communication. born on the command line, but ported to php via libcurl. $curl - curl_init('www.example.com')    
10 web services Broad term for computers interacting with each other over the web/internet. Divided into Complex and Simple. The geo-ip - is simple type, but is also RESTFUL, in that the nature of the data return is impacted by the data sent to the service/API.      
11 zlib compression allows php compression of files.

gzopen() function takes two parameters: the filename and the mode of opening. The modes correspond directly to fopen()’ s modes (w, r, a along with b for writing binary data) but can also indicate a level of compression. The acceptable compression levels are on a scale from 1 (minimal compression) to 9 (maximum) with a trade-off between compression and performance. For relatively small files like these text documents, maximum compression is fine.

gzopen('file','mode'.'complevel'), ie gzopen("$dir/{$table}_{$time}.sql.gz", 'w9')

   
11 cron unix server service to be carried out automatically

minutes hours days months day_of_week_0_to_6 cmd -option target

30 22 * * * wget -f http://example.com (means wget that page quietly every day at 10:30pm)

   
Toggle Sidebar