当前位置:首页 > PHP教程 > PHP常见问题

Laravel框架中扩展函数、扩展自定义类的方法

一、扩展自己的类

在app/ 下建立目录 librariesclass 

然后mytest.php 类名格式 驼峰 mytest

复制代码 代码如下:

<?php
class mytest
{
public  function test()
{
return '1asdasd111';
}
}

在 app/start/global.php

复制代码 代码如下:

classloader::adddirectories(array(
app_path().'/commands',
app_path().'/controllers',
app_path().'/models',
app_path().'/database/seeds',
app_path().'/libraries/class', //增加这一段
));

用 make 载入
复制代码 代码如下:

<?php
class homecontroller extends basecontroller {
    protected $layout = 'layouts.main';
public function index()
{
$a = app::make('mytest'); // 用法
echo $a->test();
}
}

二、扩展自己的函数

在app/ 下建立目录 librariesfunction

建立helper.php

函数格式,如下用function_exists,防止与系统重名

复制代码 代码如下:

if (! function_exists('test2'))
{
function test2()
{
echo 2222222222222222;
}
}

方法一:

在 app/filters.php

复制代码 代码如下:

app::before(function($request)
{
require app_path().'/libraries/function/helper.php'; //载入 自定义函数
});

方法二:

在app/bootstrap/autolad.php

复制代码 代码如下:

require __dir__.'/../app/functions.php'; // 引入自定义函数库

我感觉方法一会比较好。


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!