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.

Community
  • 1
  • 1
Himmators
  • 14,278
  • 36
  • 132
  • 223

1 Answers1

0

You don't have to extends anything for your class to be usable in laravel. As long as you file is in the composer require path, your class will be loaded by laravel.

You can extends or implements some laravel's classes to add some functionnality (facades for example) but that's not a requirement.

Additionnaly, based on the code you provided, your save function belongs more to a model than to a external helper. Helper must only contains simple methods like formatting a date or calculating some value based on some other values. You helper must contains simple function that don't use something external (in this case, an eloquent model) in order to be more dependency free (and less error prone when changing that model). Try to move that to the Post model (as a static function).

Edit: In order to call it statically (with ::), you have to make your function static as well or use laravel IoC (facade) do the job for you. (more info in the docs: http://laravel.com/docs/facades )

Atrakeur
  • 4,126
  • 3
  • 17
  • 22