Public Available Function in Laravel 4

◇◆丶佛笑我妖孽 提交于 2019-12-06 07:55:03

问题


If I would like to make a function in Laravel, that is available everywhere in my app, how would I go about that?

What I mean, is that, if I create a function called resizeimage() and would like to call it from anywhere in my Laravel application, how can I do this?


回答1:


Create a folder named: libraries

Create a file(class) in your library: Image.php

Then add this code to Image.php:

<?php

class Image{

   public static function resizeImage($image){
      return $image;
   }

}

Edit global.php in your 'start'-folder: Add app_path().'/libraries',

Example:

ClassLoader::addDirectories(array(

    app_path().'/commands',
    app_path().'/controllers',
    app_path().'/models',
    app_path().'/database/seeds',
    app_path().'/libraries',

));

Now you can call your 'function' like this 'anywhere':

Image::resizeImage('http://path/to/image');



回答2:


You could create a helpers.php file inside app and require it on app/start/global.php.

app/helpers.php

<?php

    function resizeimage() {
        // resize image
    }

app/start/global.php

// ...
// At the bottom

require app_path().'/helpers.php';


来源:https://stackoverflow.com/questions/20706641/public-available-function-in-laravel-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!