【发布时间】:2016-09-27 12:13:57
【问题描述】:
我正在 laravel 中构建一些小型 cms,现在我需要根据我的 cms 中创建的页面在我的控制器中动态命名方法和变量。我创建了几个页面:news, world, sport, business。现在我需要那些方法中的方法和变量,命名为页面名称,动态的。
这是我的 AjaxController。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Post;
use App\Tag;
use App\Page;
class AjaxController extends Controller
{
protected $posts;
protected $tags;
protected $pages;
protected $methods;
public function __construct(Post $posts, Page $pages, Tag $tags)
{
$this->posts = $posts;
$this->tags = $tags;
$this->pages = $pages;
$this->methods = $this->pages->where('parent_id', null)->where('title', '!=', 'Home')->orderBy('lft', 'asc')->get()->all();
}
foreach($this->methods as $method) {
public function {$method->name}()
{
${$method->name} = $this->posts->with('user')->with('category')->with('subcategory')->where('category_id', $method->id)->orderBy('created_at', 'desc')->paginate(3, ['*'], '{$method->name}');
return view('ajax.'.$method->name, compact('{$method->name}'))->render();
}
}
}
这对我不起作用。
我需要得到的结果应该是这样的
public function news()
{
$news = $this->posts->with('user')->with('category')->with('subcategory')->where('category_id', 8)->orderBy('created_at', 'desc')->paginate(3, ['*'], 'news');
return view('ajax.news', compact('news'))->render();
}
public function world()
{
$world = $this->posts->with('user')->with('category')->with('subcategory')->where('category_id', 10)->orderBy('created_at', 'desc')->paginate(3, ['*'], 'world');
return view('ajax.world', compact('world'))->render();
}
public function sport()
{
$sport = $this->posts->with('user')->with('category')->with('subcategory')->where('category_id', 12)->orderBy('created_at', 'desc')->paginate(3, ['*'], 'sport');
return view('ajax.sport', compact('sport'))->render();
}
...
请问,如何循环和获取类中的动态方法和变量,并在 laravel 紧凑和分页方法中解析动态变量?
【问题讨论】:
-
看看 php 中的magic class methods。特别是您想查看
__call魔术方法。但是,这些事情往往违反最佳实践。您应该将页面标识符传递给您的 AJAX 请求,以便正确处理它。 -
Ajax 只是一个例子。我在其他一些控制器中也需要动态方法 - 没有 ajax 的 php。
-
嗯,
__call魔术方法是专门为这项工作设计的,但它比标准方法慢。 -
你能给我举个例子吗?我不确定如何在 __call() 魔术方法中进行查询并将变量解析为视图?
标签: php methods dynamic laravel-5.2