[PHP] - Laravel - 列表、新增、修改、删除例子

不打扰是莪最后的温柔 提交于 2020-01-20 23:55:43

前言

Laravel默认是自带了CURD的功能,使用路由的Route::resource可以做到。

但真正的项目中,这往往不是我们所需要的。因为一个项目会有比较复杂的计算、验证等功能。

下面是对项目中的列表、新增、修改、删除写了一个简单的view层的模型例子


 

 

一、路由配置

在app\Http\routes.php加入如下:

Route::group(["prefix" => "my2"], function() {
   Route::controller("/", "my\MyTest2Controller");
});

 

二、控制器基类

在app\Http\Controllers目录下新建一php类文件:BaseController.php

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

class BaseController extends Controller
{
    public function __construct() {
        $this->beforeFilter(function() {
            $this->before();
        });
    }
    
    protected function before() {
    }
}

?>

 

三、视图模型

视图模型基类

在app\models目录下新增php类文件:BaseModel.php (Laravel 5好像默认没有这个目录,需要自已新建)

<?php
namespace App\models;

use Validator;

/**
 * Model基类
 * @author Robin
 *
 */
abstract class BaseModel
{
    /**
     * 验证类
     * @var Validator
     */
    private $_validator;
    
    /**
     * 错误验证信息
     * @var Array
     */
    protected $messages = [
        "integer" => "应为整型值",
        "required" => "必填字段",
        "confirmed" => "密码两次输入不一致",
        "email" => "邮件地址格式不正确",
        "date" => "日期格式不正确",
        "between" => "值区间为:min 到 :max",
        "min" => "最小值为:min",
        "max" => "最大值为:max",
        "in" => "值应为:values",
        "size" => "大小为:size",
    ];
 
    /**
     * 加载函数
     * @param Input $input
     * @param Rule $rule
     */
    protected function init($input, $rule = array())
    {
        $this->_validator = Validator::make($input, $rule, $this->messages);
 
        $formKey = array_keys(get_class_vars(get_class($this)));
        // 遍历表单键值 并赋予类成员
        foreach ($formKey as $value)
        {
            if(isset($input[$value]))
            {
                $this->$value = $input[$value];
            }
        }
    }
 
    /**
     * 取得验证器
     */
    public function validator()
    {
        return $$this->_validator;
    }
 
    /**
     * 判断是否验证成功
     * @return boolean
     */
    public function isValid()
    {
        return !$this->_validator->fails();
    }
    
    /**
     * 取得验证错误信息
     */
    public function messages() {
        return $this->_validator->messages();
    }
 
}

?>

 

视图模型类

在app\models目录下新建my2目录,在my2目录下新建php类:MyUser.php

<?php
namespace App\models\my2;

use App\models\BaseModel;

class MyUser extends BaseModel
{
    public $id;
    public $name;
    public $email;
    public $age;
    public $birthday;
    public $password;
    public $password_confirmation;
    public $homepage;
    
    public function __construct() {
        
    }
    
    public function convert($input) {
        //-----------------------------------------------------
        // 字段验证
        //-----------------------------------------------------
        $rule = array(
            "name" => "required|min:4|max:10",
            "email" => "required|email",
            "age" => "required|integer|between:1,100",
            "birthday" => "required|date",
            "password" => "required|between:6,12|confirmed",
            "password_confirmation" => "required",
            "homepage" => "required|regex:/^http:\/\/.+/",
        );
        
        //-----------------------------------------------------
        // 加入自定义验证错误信息
        //-----------------------------------------------------
        $selfMessages = [
            "homepage.regex" => "主页地址不正确",
            "name.min" => "最小:min个字符",
            "name.max" => "最多:max个字符",
        ];
        $this->messages = array_merge($this->messages, $selfMessages);
        
        //-----------------------------------------------------
        // 调用父类方法
        //-----------------------------------------------------
        $this->init($input, $rule);
    }
}

?>

由于Laravel是没有直接对用户提交的数据映射成model的功能,所以写了一个模型基类做这个事。当然,这个基类也包括了对模型的数据验证。

 

四、控制器

在app\Http\Controllers目录下新建目录my2,在my2目录下新建php类文件:MyTest2Controller.php

<?php
namespace App\Http\Controllers\my;

use App\models\my2\MyUser;
use App\Http\Controllers\BaseController;
use Redirect;
use Route;
use View;
use Input;
use Request;
use URL;
use Session;
use Response;

class MyTest2Controller extends BaseController
{
    /**
     * 设置路径
     */
    private $path;

    function __construct()
    {
        $this->path = [
            "add" => URL::action("my\MyTest2Controller@getAdd"),
            "edit" => URL::action("my\MyTest2Controller@getEdit"),
        ];
    }
    
    public function getIndex() {
        $data = array(
            ["id" => 1, "name" => "robin"],
            ["id" => 2, "name" => "zhang"]
        );
        // 取得当前路由名称,如在路由中没有指定名称,返回空
        //$route = Route::currentRouteName();
        // 取得当前请求地址
        //$route = Request::url();
        // 取得当前请求路径
        // $path = Request::path();
        // 取得指定方法的Action
        // $action = action('my\MyTest2Controller@getAdd');
        // 取得指定方法的URL
        // $url = URL::action('my\MyTest2Controller@getEdit');
        
        return View::make("my.MyList", ["data" => $data, "path" => $this->path]);
    }
    
    public function getEdit($id) {
        $myUser = new MyUser();
        $myUser->id = $id;
        return View::make("my.MyEdit", ["user" => $myUser, "path" => $this->path]);
    }
    
    public function postEdit($id) {
        return $this->save($id);
    }
    
    public function getAdd() {
        return View::make("my.MyEdit", ["user" => new MyUser(), "path" => $this->path]);
    }
    
    public function postAdd() {
        return $this->save(0);
    }
    
    private function save($id) {
        $myUser = new MyUser();
        $myUser->id = $id;
        // -----------------------------------------------
        // 将输入值转换为对象
        // -----------------------------------------------
        $myUser->convert(Input::All());
        
        // -----------------------------------------------
        // 验证输入
        // -----------------------------------------------
        if($myUser->isValid()) {
            if($myUser->id == 0) {
                // TODO:
                // 新增
            }
            else {
                // TODO:
                // 更新
            }
            // 成功后重定向
            //return redirect()->to("/my2");
            return redirect()->action("my\MyTest2Controller@getIndex");
        }
        else {
            // 输入验证错误,返回view
            return View::make("my.MyEdit", ["user" => $myUser, "messages" => $myUser->messages(), "path" => $this->path]);
        }
    }
}

?>

 

五、视图

在resources\views\目录下新建my目录,新建php文件:MyList.blade.php

<h1>List page:</h1>
<?php
    foreach ($data as $item) {
        echo($item["name"]);
    }
?>
<br/>
<a href="{{$path['add']}}">Add user</a>
<br/>
@foreach($data as $item)
    <p>ID={{$item["id"]}}, Name={{$item["name"]}}, <a href="{{$path['edit']}}/{{$item["id"]}}">edit</a></p>
@endforeach

同样,新建php文件:MyEdit.blade.php

<?php
?>
@if (isset($messages))
<p>输入错误:</p>
<ul>
    @foreach($messages->all() as $item)
        <li style="color: red;">{{$item}}</li>
    @endforeach
</ul>
<hr/>
@endif
<form name="myform" action="{{$user->id>0 ? $path['edit'].'/'.$user->id : $path['add']}}" method="post">
    User name:<input name="name" type="text" value="{{$user->name}}" />{!!isset($messages) ? $messages->first('name', '<span style="color:red;">:message</span>') : ""!!}<br/>
    Email:<input name="email" type="text" value="{{$user->email}}" />{!!isset($messages) ? $messages->first('email', '<span style="color:red;">:message</span>') : ""!!}<br/>
    Age:<input name="age" type="text" value="{{$user->age}}" />{!!isset($messages) ? $messages->first('age', '<span style="color:red;">:message</span>') : ""!!}<br/>
    Birthday:<input name="birthday" type="text" value="{{$user->birthday}}" />{!!isset($messages) ? $messages->first('birthday', '<span style="color:red;">:message</span>') : ""!!}<br/>
    Password:<input name="password" type="password" value="{{$user->password}}" />{!!isset($messages) ? $messages->first('password', '<span style="color:red;">:message</span>') : ""!!}<br/>
    Confirm Password:<input name="password_confirmation" type="password" value="{{$user->password_confirmation}}" />
        {!!isset($messages) ? $messages->first('password_confirmation', '<span style="color:red;">:message</span>') : ""!!}<br/>
    Home page:<input name="homepage" type="text" value="{{$user->homepage}}" />{!!isset($messages) ? $messages->first('homepage', '<span style="color:red;">:message</span>') : ""!!}<br/>
    <input type="submit" value="save" />
</form>

 

运行效果

列表页

 

新增页

 

保存验证页

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!