Skip to content

Instantly share code, notes, and snippets.

@deadcheat
Created September 21, 2016 12:14
Show Gist options
  • Save deadcheat/ce82c7492cfb16d6dff30be6aa42250f to your computer and use it in GitHub Desktop.
Save deadcheat/ce82c7492cfb16d6dff30be6aa42250f to your computer and use it in GitHub Desktop.
自作のModelサンプル
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ExampleTest extends TestCase
{
/**
* A basic functional test example.
*
* @return void
*/
public function testBasicExample()
{
$model = new \App\Http\Models\Naomi();
$model->name = 'Naomi';
$model->status = 'retired';
var_dump(print_r($model, true));
var_dump($model->name);
var_dump($model->status);
}
}
<?php
namespace App\Http\Models;
// SuperModelの継承。おっさんなのでNaomiしか思いつかなかった
class Naomi extends SuperModel
{
protected $_columns = [
// name
'name',
// career status
'status'
];
}
<?php
namespace App\Http\Models;
class SuperModel
{
// 内部でKey-Valueを持つ箱
protected $_innerMap = [];
// Validate用に、設定できる項目を指定する
protected $_columns = [];
/**
* @param $name string キー名
* @return mixed|null ※ このReturnは適宜使いやすいように改変したほうが良い
*/
public function __get($name)
{
$this->validate($name);
if (array_key_exists($name, $this->_innerMap)) {
return $this->_innerMap[$name];
} else {
return null;
}
}
/**
* @param $name string キー名
* @param $value mixed 設定するバリュー
*/
public function __set($name, $value)
{
$this->validate($name);
$this->_innerMap[$name] = $value;
}
/**
* @param $key string キー名 $_columnsへの存在チェックを行う
*/
protected function validate($key) {
if (!in_array($key, $this->_columns)) {
throw new \InvalidArgumentException("{$key} is not valid element of " . get_class($this));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment