Skip to content

Instantly share code, notes, and snippets.

@zymsys
Created April 8, 2012 15:53
Show Gist options
  • Save zymsys/2338113 to your computer and use it in GitHub Desktop.
Save zymsys/2338113 to your computer and use it in GitHub Desktop.
SOLID Sample Code
<?php
class FooControllerConventional
{
function indexView() {
$model = new FooModel();
$viewData = $model->fetchAll();
$view = new FooView();
$view->render($viewData);
}
}
class FooControllerDI
{
private $_model;
private $_view;
function __construct(FooModel $model, FooView $view) {
$this->_model = $model;
$this->_view = $view;
}
function indexView() {
$viewData = $this->_model->fetchAll();
$this->_view->render($viewData);
}
}
interface ViewServiceInterface {
function render($viewData);
//... Other required methods
}
interface ModelServiceInterface {
function fetchAll();
// ... Other required methods
}
class FooControllerDIP
{
private $_model;
private $_view;
function __construct(ModelServiceInterface $model,
ViewServiceInterface $view) {
$this->_model = $model;
$this->_view = $view;
}
function indexView() {
$viewData = $this->_model->fetchAll();
$this->_view->render($viewData);
}
}
public class UserModel {
public String doLogin(String userID, String password) {
/* ... */
return "authToken";
}
public Boolean authenticate(String authToken) {
/* ... */
return true;
}
}
public interface ILoginService {
String doLogin(String userID, String password);
}
public interface IAuthenticationService {
Boolean authenticate(String authToken);
}
public class UserModel implements ILoginService, IAuthenticationService {
@Override
public String doLogin(String userID, String password) {
/* ... */
return "authToken";
}
@Override
public Boolean authenticate(String authToken) {
/* ... */
return true;
}
}
using System;
namespace ScratchConsoleApp
{
class Duck {
public void Fly() { /* ... */ }
}
class DecoyDuck : Duck {
public new void Fly()
{
throw new Exception("Decoy ducks don't fly.");
}
}
class Program
{
static void Main(string[] args)
{
var duck = new DecoyDuck();
duck.Fly();
}
}
}
//LSP Violation Example - Covariant parameter
//BarModel extends FooModel
public class FooView {
void display(FooModel foo) { /* ... */ }
}
public class BarView extends FooView {
void display(BarModel foo) { /* ... */ }
}
class FooMapper:
"""Returns a set."""
def fetchAll(self):
return ['a', 'b', 'c']
class BarMapper (FooMapper):
"""Returns a tupple."""
def fetchAll(self):
return ('a', 'b', 'c')
foo = FooMapper()
bar = BarMapper()
fooItems = foo.fetchAll()
barItems = bar.fetchAll()
print fooItems, barItems
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment