如何从其他方法访问变量?或者如何做得更好?

时间:2017-05-08 22:35:52

标签: php laravel

我想知道除了在我的控制器中重复我的请求之外还有其他方法。我有一个函数show($slug),里面有一个查询,它接受变量$teacher

protected function show($slug)
{
    $teacher = Teacher::where('slug', $slug)->firstOrFail();

    return view('posts.postTeacher', [
        'teacher' => $teacher,
        'imageProfile' => $this->getImageProfile($slug)
    ]);
}

我创建了另一个功能来管理我的图像。只是,我不知道如何访问另一种方法的varialbe $ teacher。然后我不得不用$ slug创建一个新的。

public function getImageProfile($slug)
{
    $teacher = Teacher::where('slug', $slug)->firstOrFail();

    $basePath = 'uploads/teachers/';
    $fullname = pathinfo($teacher->picture, PATHINFO_FILENAME);
    $imageProfile = $basePath . $fullname . '_profile.jpg';

    return $imageProfile;
}

有更好的方法吗?

3 个答案:

答案 0 :(得分:3)

为什么不在getImageProfile - 类?

中移动Teacher
class Teacher extends Model {

    // ....

    public function getImageProfile()
    {
        $basePath = 'uploads/teachers/';
        $fullname = pathinfo($this->picture, PATHINFO_FILENAME);
        return $basePath . $fullname . '_profile.jpg';
    }

}

protected function show($slug) {
    $teacher = Teacher::where('slug', $slug)->firstOrFail();

    return view('posts.postTeacher', [
        'teacher' => $teacher,
        'imageProfile' => $teacher->getImageProfile()
    ]);
}

将逻辑事物分组在一起,使用起来更轻松

答案 1 :(得分:1)

您的第二种方法可以将$fullname作为输入参数:

protected function show($slug)
{
    $teacher = Teacher::where('slug', $slug)->firstOrFail();
    $fullname = pathinfo($teacher->picture, PATHINFO_FILENAME);

    return view('posts.postTeacher', [
        'teacher' => $teacher,
        'imageProfile' => $this->getImageProfile($slug, $fullname)
    ]);
}

public function getImageProfile($slug, $profilePrefix)
{
    $basePath = 'uploads/teachers/';
    $imageProfile = $basePath . $profilePrefix . '_profile.jpg';

    return $imageProfile;
}

答案 2 :(得分:1)

您应该可以使用Route-Model Binding(如here所述)来完成此操作。您可以向教师模型添加一个方法,指定您使用slug(而不是id,这是默认值):

public function getRouteKeyName()
{
    return 'slug';
}

通过这种方式,您可以设置路线以查找slug并拉出教师模型的相应实例,以便在控制器方法中使用。

// in your routes file
Route::get('teachers/{teacher}', 'TeachersController@show');

// in your controller
protected function show(Teacher $teacher)
{
    $imageProfile = $teacher->getImageProfile();
    return view('posts.postTeacher', compact('teacher', 'imageProfile'));
}

// in model
public function getImageProfile()
{
    $basePath = 'uploads/teachers/';
    $fullname = pathinfo($this->picture, PATHINFO_FILENAME);
    $imageProfile = $basePath . $fullname . '_profile.jpg';

    return $imageProfile;
}