Propel使用Peer
类,并且使用Table
类作为操作相应对象和对象属性的方法,而不必使用static
方法污染实际对象。
粗略地浏览一下laravel(雄辩)文档后,我没有看到任何雄辩提供相同Peer
或Table
类似功能的内容。我的问题是,laravel(或eloquent)是否为这些类提供了命名空间,或者我只是使用Table
并让autoloader负责其余的工作?
// Example use of a table class in doctrine 1.2
$user = UserTable::getInstance()->findById(1);
- 更新1 -
如何使用教义表类的Layman示例:
class UserTable
{
public static function getInstance()
{
return Doctrine_Core::getTable('User');
}
public function linkFoo($userId, array $foos)
{
$user = $this->findById($userId);
foreach ($foos as $foo) {
$user->foo = $foo;
$user->save();
}
}
}
// SomeController.php
executeSaveFoo()
{
UserTable::getInstance()->linkFoo($this->getUser(), array('foo1', 'foo2'));
}
doctrine table类的目的是为不应该在控制器中的各个对象提供操作的api,在上面的示例中,linkFoo
类将提供的foos链接到相应的用户对象。< / p>
我觉得对象和'table'类之间的分离很重要,因为对象不应该知道如何实例化和自我保湿。
答案 0 :(得分:5)
如前所述,完成任务的方法不止一种,但这是一个使用命令的快速示例。
<强>控制器强>
namespace App\Http\Controllers;
//...
use App\Http\Requests\UpdateUserRequest;
use App\Commands\UpdateUser;
use App\User;
//...
class UserController extends Controller {
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update(UpdateUserRequest $request, $id)
{
//gather request data
$data = $request->all();
//retrieve user
$user= User::findOrFail($id);
//update user
$updateUser = \Bus::dispatch(
new UpdateUser($user, $data)
);
//check if update was successful
if($updateUser)
{
//update successful
return redirect('/route/here')->with('message', 'User updated successfully');
}
else
{
//else redirect back with error message
return redirect()->back()->with('error', 'Error updating user');
}
}
}
UpdateUserRequest
类将处理验证。
<强>命令强>
namespace App\Commands;
use App\Commands\Command;
use Illuminate\Contracts\Bus\SelfHandling;
class UpdateUser extends Command implements SelfHandling {
protected $user, $data;
/**
* Create a new command instance.
*/
public function __construct($user, $data)
{
$this->user= $user;
$this->data = $data;
}
/**
* Execute the command.
*/
public function handle()
{
//assign first name
$this->user->first_name = $this->data['first_name'];
//assign last name
$this->user->last_name = $this->data['last_name'];
//assign email address
$this->user->email = $this->data['email'];
//update user
if($this->user->update())
{
//updated successfully, return true
return true;
}
else
{
//else return false
return false;
}
}
}