The helpful design patterns

Warning! This post is either deprecated or outdated.

The use of patterns in code being a good enhancement isn’t big news. But I discovered them recently and am very positive about it. It can, when understood, hugely increase your readability and is a nice problem solver for complicated and extendible coding.

Before creating a design pattern, you have to create it on paper. Think about what pattern you can use before implementing one. There are different patterns, every one of them has specific needs and specifications.

For example:

  • Observer Pattern
  • Decorator Pattern
  • Factory Pattern
  • Command Pattern
  • etc…

In our case we needed to build a good nice 5-step wizard that is perfect to use simple pattern structure.

For us, it made the code very easy to understand and realy clean. We created one controller that gets the correct action when initialized , and it initializes the correct class (step) by itself.

$controller = new StepController();
$controller ->getInstance($action);

stepcontroller.class.php

public function getInstance($currentAction = null) {

$stepAction = null;

switch($currentAction) {
case "step1" :
$stepAction = new step1Action();
break;
case "step2" :
$stepAction = new step2Action();
break
}

return $stepAction->execute();
}

All the action classes have a execute function on their own and implement an interface that contains the execute function.

By using this kind of pattern it is very easy for us to add or remove steps in our little wizard. Every step has its own action and is really easy to maintain.
As you can see (and this is only one little example) the patterns have great advantages, the only challenge is to know what pattern to be used best in your specific situation.

Have fun with it.

By the way, if you found a typo, please fork and edit this post. Thank you so much! This post is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Comments

Fork me on GitHub