Categories
PHP Wordpress

Adding actions to wordpress based on events

add_action($tag, $function_to_add, $priority, $accepted_args);
add_filter($tag, $function_to_add, $priority, $accepted_args);

The $tag parameter is where you specify the hook you want to add to; $function_to_add is the name of your function. The next two are optional, but worth knowing about: $priority is used to determine the order in which your action ought to occur, relative to other actions that might be happening on the same hook—larger numbers happen later. $accepted_args

And to remove them (notice you have to do this indirectly):

function remove_some_filter() {
  remove_filter(tag, function, priority, args);
}

add_action('init', 'remove_some_filter')


Example:

add_action('wp_head', 'wicked_favicon')

This runs everytime the page head is constructed, you can have the specific function inside functions.php:

function wicked_favicon() {
  echo '<link rel="shortcut icon" href="' 
      . get_bloginfo('stylesheet_directory') 
      . '/images/favicon.ico"/>';
}

Categories
Wordpress

WordPress: choosing and modifying a theme

1) Download thematic (as the parent theme)
2) Create a child theme folder for the new site, and activate it using wordpress admin screen
3) Choose the basic layout you need, by modifying this line:
@import url(‘../thematic/library/layouts/2c-r-fixed.css’);
You can also create your own layout at this point if you feel like it. Same with typography or other things.
4) You can also modify the default main css to your site by creating a local copy on your child theme:
@import url(‘newstyles.css’);
5) Modify the templates and functions from the parent directory directly at the child’s folder, that way
you can always update the parent theme without affecting the child

Correction: 20/11 newest wordpress theme is set to be HTML5 already. Use that instead.

Categories
PHP

PHP __toString() method

Useful to convert objects that, when printed (say in debugging), will give you output like “Resource ID blah blah”, or error messages telling you you can’t print the object.

Example:

class Person {
    function getName()  { return "Bob"; }
    function getAge() { return 44; }
    function __toString() { // Controls how this object will represent itself when printed
        $desc  = $this->getName();
        $desc .= " (age ".$this->getAge().")";
        return $desc;
    }
}
$person = new Person();
print $person; // We get the printout defined in __toString() here...
Categories
PHP

PHP Error handling

When there are problems, always return an Exception object to the client.

Exception constructor accepts two optional arguments: an error string (error description in “plain english”) and an error code.

These are the Exception object’s public methods available:

  • getMessage() – Get the message string that was passed to the constructor.
  • getCode() – Get the code integer that was passed to the constructor.
  • getFile() – Get the file in which the exception was generated.
  • getLine() – Get the line number at which the exception was generated.
  • getTrace() – Get a multidimensional array tracing the method calls that led to the exception, including method, class, file, and argument data.
  • getTraceAsString() – Get a string version of the data returned by getTrace().
  • __toString() – Called automatically when the Exception object is used in string context. Returns a string describing the exception details.

The “throw” keyword basically stops the current method’s execution, passing an Exception object back to the calling client, and expecting it to handle the exception problem raised.

Error handling best practices call for subclassing Exceptions, so you have an exception per type of error, and handle the problem according to the exception type:

class XmlException extends Exception {
    private $error;

    function __construct( LibXmlError $error ) { // In this case we are expecting a LibXmlError already, but not
           // neecesary to have Type Hinting here
        $shortfile = basename( $error->file );
        $msg = “[{$shortfile}, line {$error->line}, col {$error->col}] {$error->message}”;
 $this->error = $error;
      parent::__construct( $msg, $error->code ); // Exception parent class is still called
    }

  function getLibXmlError() {
      return $this->error;
  }
}

class FileException extends Exception { } // Classes not “filled out yet”, but they will handle
class ConfException extends Exception { } // other kind of exceptions simmilar to XmlException

A typical client code that takes care of multiple exception types will look like this:

class Runner {
     static function init() {
        try {
            $conf = new Conf( dirname(__FILE__).”/conf01.xml” );
            print “user: “.$conf->get(‘user’).”n”;
            print “host: “.$conf->get(‘host’).”n”;
            $conf->set(“pass”, “newpass”);
            $conf->write();
        } catch ( FileException $e ) {
           // permissions issue or non-existent file
        } catch ( XmlException $e ) {
           // broken xml
        } catch ( ConfException $e ) {
           // wrong kind of XML file
        } catch ( Exception $e ) {
           // backstop: should not be called
        }
    }
}

When you have multiple catches this way, the first catch that matches the Exception type will be executed, so always try to put the more generic errors at the end. At this point, when an exception is catched, you can throw it again for further handling in subsequent catches.

Categories
PHP Programming

PHP interfaces

Interfaces are pure class templates that define functionality. It can contain properties and methods, but no method implementation. See the example below:

interface Chargeable {
    public function getPrice();
}

So any class that implements this interface, will look something like this:

class ShopProduct implements Chargeable {
    // …
    public function getPrice() {
    return ( $this->price – $this->discount );
    }
    // …

When a class implements an interface, it takes on the Type of the interface as well, effectively having more than two types if that same class is also extending other classes, or implementing other interfaces. This way you can join types that are otherwise unrelated when creating a new class.

In PHP you can only inherit from one parent, but you can have multiple interfaces:

class Consultancy extends TimedService implements Bookable, Chargeable {

    // ...
}
Categories
PHP Programming

Public, private and protected methods and variables.

  • Public: access from everywhere.
  • Private: access is only permitted from inside the instantiated object.
  • Protected: accessed is permitted from inside the instantiated object, or from objects that are subclasses of the current object.
Categories
PHP Programming

OOP Best Practices and architecture

  1. When creating classes, make a really general abstaction of the object you have in mind (usually an abstact class or interface), and then start working your way down to the specifics using inheritance, encapsulation and polymorphism. For example: to create a book object for an ecommerce site, create something like Product / Item / Books / Book.
    • Advantages: This way your architecture can accomodate other objects later (cars / clothes / other categories)
    • Inside your classes, you avoid using hard to maintain “If” flags and clauses to perform different tasks per type of class
    • At the same time, you maintain a hierarquical structure of your objects that help you control variables and methods per level.
    • Make sure your classes are not overloaded with responsibilities. Spread responsibilities around the hierarquical structure of classes, if you can’t define a class responsibility with 25 words, and without using “and” and “or” words, you may be overloading your class with tasks. This will be hard to maintain.
    • But always remember: OOP best practices are not set on stone. If you have a good reason to bend the rules (performance, etc), do it, but think hard before you go ahead.
  2. As a general safety rule, you can set all methods and variables to private, and start resetting them to protected or public as you go along.
  3. Add error handling to all places things can go wrong (unexpected input / output usually). See PHP Error Handling section for more details, but basically extend the provided Exception class with a new class for each kind of error, and at the catch part of your try catch statement, have several catches that will deal with the particular error the proper way based on Exception type detection.
  4. Here are four possible indications of design problems:
    1. Code duplication: if you get a deja vu feeling at code writing a class, think: if I change something fundamental in this routine, will the other simmilar routine need ammendments? If so, then you may have a dup class you can compress in one.
    2. If a class depends too much on Globals variables and its context, this class will be hard to maintain. Try to make each class its own environment.
    3. If a class is doing too much, think of ways to reduce responsibility and extend down to other classes.
    4. Testing for the same condition with “if” statements throughout diffent classes may call to review your polymorphism. Where you can do the “if” test once, and spawn different objects with no “if” conditions down that fork
  5. Inside your classes, seek for those lines of code that express variation and fork the behavior of the current class given different values or conditions, and try to encapsulate them in their own type class.
  6. The golden rules: “Do the simplest thing that work”, and “are you sure you are going to need this extra complexity?”
  7. Avoid global variables like the plague, they make your classes highly coupled with the system, can’t be reused easily, and it’s hard to encapsulate stuff when using those. If you are to use Globals (say, to avoid passing too many variables or objects around) use singletons instead.
  8. Use phpDocumentor to add documentation to your code, even the default, do nothing and just run it option is better than nothing: http://www.phpdoc.org/
  9. Make sure you include Unit testing with PHPUnit
Categories
PHP Programming

PHP instanceof to determine what kind of object we are dealing with

Example:

class ShopProductWriter {
    public function write( $shopProduct ) {
        if ( ! ( $shopProduct instanceof CdProduct )  &&
             ! ( $shopProduct instanceof BookProduct ) ) {
            die( "wrong type supplied" );
        }
         $str  = "{$shopProduct->title}: " .
                $shopProduct->getProducer() .
                " ({$shopProduct->price})n";
        print $str;
    }
}
Categories
PHP Programming

PHP Object type hinting

Introduced with PHP 5.1, it basically looks like this:

function setWriter( ObjectWriter $objwriter=null ) {
    $this->writer = $objwriter;
}

Where the $objwriter has to be either null or of the type ObjectWriter, or it will produce a runtime error. The =null part is optional.

Advantages:

Forces to pass the right kind of object to a method, saving us the trouble of testing before passing. It also makes the code clearer regarding method signature.

Disadvantage:

Since it only runs at runtime, if it is buried within conditional statements that only run on xmas, you may get a call on your holiday to get your budd to the office and fix it.

Not that you can’t use type hinting with primitives.

Categories
PHP

PHP abstract classes

Basically, abstract classes define methods but don’t have any functionality inside of them, and can’t be instantiated directly. They are just blueprints for classes that extend them, inheriting their methods (and being forced to define them). Abstract classes can’t be instantiated, just extended.