分享一个TP5实现Create()方法的心得

在TP5中发现用不了以前3.X的Create()方法,虽然用input更严谨,但是字段比较多的话还是有些不艺术的
3.X中的实现方法如下:

$Model = D('User');
$Model->create();
$Model->add();

在仔细阅读了TP5文档后,发现有这么一段:

欣喜之余便测试了一下,发现返回的内容是个类,不能直接做修改,只能接着连贯操作:

appcategorymodelCategory Object
(
    [connection:protected] => Array
        (
        )
    [name:protected] => Category
    [table:protected] => 
    [class:protected] => appcategorymodelCategory
    [pk:protected] => 
    [error:protected] => 
    [validate:protected] => 
    [field:protected] => Array
        (
        )
    [visible:protected] => Array
        (
        )
    [hidden:protected] => Array
        (
        )
    [append:protected] => Array
        (
        )
    [data:protected] => Array
        (
            [title] => dd
            [sort] => 1
            [pcid] => 0
        )
    [change:protected] => Array
        (
        )
    [auto:protected] => Array
        (
        )
    [insert:protected] => Array
        (
        )
    [update:protected] => Array
        (
        )
    [autoWriteTimestamp:protected] => 
    [createTime:protected] => create_time
    [updateTime:protected] => update_time
    [deleteTime:protected] => delete_time
    [dateFormat:protected] => Y-m-d H:i:s
    [type:protected] => Array
        (
        )
    [isUpdate:protected] => 
    [updateWhere:protected] => 
    [relation:protected] => 
    [failException:protected] => 
)

仔细看了一下,当中有这么一段是我post的数据:

    [data:protected] => Array
        (
            [title] => dd
            [sort] => 1
            [pcid] => 0
        )

  翻看了一下tp5的model类,有这么一个方法:

/**
     * 获取对象原始数据 如果不存在指定字段返回false
     * @access public
     * @param string $name 字段名 留空获取全部
     * @return mixed
     * @throws InvalidArgumentException
     */
    public function getData($name = null)
    {
        if (is_null($name)) {
            return $this->data;
        } elseif (array_key_exists($name, $this->data)) {
            return $this->data[$name];
        } else {
            throw new InvalidArgumentException('property not exists:' . $this->class . '->' . $name);
        }
    }

调用了一下,果然可以获取到post的数组了。
实现代码如下:

$data = new Category($_POST);
$data = $data->getData();
原文地址:https://www.cnblogs.com/liuyi2614/p/5755457.html