-
Notifications
You must be signed in to change notification settings - Fork 0
Model
axios edited this page Jan 15, 2021
·
10 revisions
Get details from the \tpr\Model code.
Provide inheritance to model subclasses
namespace app\index\model;
use tpr\Model;
class CustomModel extends Model
{
public string $foo = "bar";
public ?string $optional_property = null;
// see https://github.com/rakit/validation#custom-validation-message
protected array $_rules = [
'foo' => 'required|lowercase'
];
// see https://github.com/rakit/validation#custom-validation-message
protected array $_messages = [
'foo:required' => ''
];
// see https://github.com/rakit/validation#custom-validation-message
protected array $_alias = [];
}
$model = new CustomModel();
$model->unmarshall([
'foo' => 'bar',
]); // unmarshall from array
// to string
(string) $model
// serialize
serialize($model)
// unserialize
unserialize($model)
// to array
$model->toArray()
// to JSON string
$model->toJson()
// get properties list
$model->properties()
// validate
$model->validate(bool $throw_exception = false)
// use as array
count($model)
isset($model["foo"])
unset($model["foo"])
$model["foo"] = "bar"
$res = $model["foo"]
- Instance
Model
from the database data
// use axios/tpr-db for example
$data = Db::name('table_name')->where('id', 1)->find();
$model = new CustomModel($data); // unmarshall from some data
- Validate params of request
namespace app\index\controller;
use tpr\Controller;
use tpr\Model;
class ParamsModel extends Model {
public string $required_param = '';
protected array $_rules = [
'required_param' => 'required'
];
protected array $_messages = [
'foo:required' => 'required :attribute'
];
protected array $_alias = [];
}
class Index extends Controller
{
public function index()
{
$model = new ParamsModel($this->request->params());
$validation = $model->validate();
if($validation->fails()){
// $this->error(int $code, string $message);
$this->error(404, $validation->errors()->firstOfAll());
}
}
}
Anything unclear or inaccurate? Please let me know at axioscros@aliyun.com