Skip to content

Instantly share code, notes, and snippets.

@hiromi2424
Created March 4, 2011 19:05
Show Gist options
  • Save hiromi2424/855496 to your computer and use it in GitHub Desktop.
Save hiromi2424/855496 to your computer and use it in GitHub Desktop.
service model example for CakePHP
<?php
class AppController extends Controller {
var $uses = array('Service');
}
<?php
class AppShell extends Shell {
var $uses = array('Service');
function postByEmail() {
$data = array(); // some email receiving process
return $data;
}
}
<?php
class Article extends AppModel {
function add() {
}
}
<?php
App::import('Shell', 'AppShell');
class ArticleShell extends AppShell {
function add() {
$data = $this->postByEmail();
if (!$this->Service->saveNewArticle($data)) {
$this->log($data);
// delivering failed notice email
}
}
}
<?php
class ArticlesController extends AppController {
function add() {
if (!empty($this->data)) {
if ($this->Service->saveNewArticle($this->data)) {
$this->Session->setFlash(__('Article has been saved.', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('Article was not saved. Please, try again.', true));
}
}
}
}
<?php
class Service extends Overloadable2 {
function get__($name) {
return $this->$name = ClassRegistry::init($name);
}
function set__($name, &$val) {
return $this->$name =& $val;
}
function saveNewArticle($data) {
return $this->Article->add($data);
}
}
<?php
App::import('Model', 'Article');
Mock::generate('Article');
class ServiceTest extends CakeTestCase {
function startTest() {
$Article =& ClassRegistry::init('MockArticle');
ClassRegistry::addObject('Article', $Article);
$this->Service = ClassRegistry::init('Service');
}
function endTest() {
unset($this->Service);
ClassRegistry::flush();
}
function testSaveNewArticle() {
$this->Service->Article->expectOnce('add');
$this->Service->saveNewArticle(array(
'title' => 'test title',
'body' => "test\nbody",
));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment