从 Laravel Controller 中删除重复代码的最佳方法是什么?在我的特殊情况下,我有博客 Controller ,其中每个子页面(索引页面、关于、联系人、单个帖子页面......)都有多个功能。在这些函数中的任何一个中,我都有一些重复的代码。我可以创建一个特殊的函数,然后我可以调用任何函数吗?
class BlogController extends Controller {
public function getIndex() {
$blogs = Blog::orderBy('id', 'desc')->where('status', '1')->paginate(3);
return view('index-page')->withBlogs($blogs);
}
public function getAbout() {
$blogs = Blog::orderBy('id', 'desc')->where('status', '1')->paginate(3);
return view('about-page')->withBlogs($blogs);
}
}
现在,我想通过创建一个特殊函数来删除重复代码(我的代码只是示例,真正的重复代码要长得多)。这甚至可能吗?除了创建另一个函数之外,还有其他方法吗?也许我可以在 Wordpress 中创建类似 function.php 的东西?
最佳答案
您可以在 Controller 文件中创建另一个函数并调用它:
private function foo($view)
{
$blogs = Blog::orderBy('id', 'desc')->where('status', '1')->paginate(3);
return view($view)->withBlogs($blogs);
}
然后调用它:
public function getIndex() {
return $this->foo('index-page');
}
public function getAbout() {
return $this->foo('about-page');
}
如果你想创建一个可以随处调用的函数,你可以创建一个
static
类中的函数。前任:public static function foo()
{
return "foo";
}
然后调用它:
NameOfClass::foo();
关于php - Laravel Controller - 在另一个函数中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47821738/