0

Based on the recommendtations in theese answers: What are the best practices and best places for laravel 4 helpers or basic functions?

I have created a file app/library/sitehelpers.php and added it to the application. What should my class extend and how do I refeence it in a controller?

<?php

    class SiteHelpers{

    function save($type, $postid, $url, $author, $content)
    {
        $post = new Post;
        $post->type = $type;
        $post->postid = $postid;
        $post->url = $url;
        $post->author = $author;
        $post->content = $content;
        try
        {
        $post->save();
        echo $post;
        }catch(Exception $e){
            throw new Exception( 'Already saved', 0, $e);
        } 
    }
}

I try to reference it like this in a controller:

public function savepostController($type, $postid, $url, $author, $content)
{
    SiteHelpers::save($type, $postid, $url, $author, $content);
}

but I get Controller method not found.

4

1 回答 1

0

您不必为您的类扩展任何东西就可以在 laravel 中使用。只要你的文件在 composer require 路径中,你的类就会被 laravel 加载。

您可以扩展或实现一些 laravel 的类以添加一些功能(例如外观),但这不是必需的。

此外,根据您提供的代码,您的保存功能更多地属于模型而不是外部帮助器。Helper 必须只包含简单的方法,例如格式化日期或根据其他值计算某个值。你的助手必须包含不使用外部东西的简单函数(在这种情况下,一个雄辩的模型),以便更加无依赖(并且在更改该模型时更不容易出错)。尝试将其移至 Post 模型(作为静态函数)。

编辑:为了静态调用它(使用 ::),您必须使您的函数也静态或使用 laravel IoC(外观)为您完成这项工作。(文档中的更多信息:http: //laravel.com/docs/facades

于 2013-08-19T09:08:17.597 回答