我想创建帮助函数,以避免在Laravel视图之间重复代码。例如:
view.blade.php
<p>Foo Formated text: {{ fooFormatText($text) }}</p>
它们基本上是文本格式化函数。我应该如何定义全局可用的帮助函数,如fooFormatText()?
我想创建帮助函数,以避免在Laravel视图之间重复代码。例如:
view.blade.php
<p>Foo Formated text: {{ fooFormatText($text) }}</p>
它们基本上是文本格式化函数。我应该如何定义全局可用的帮助函数,如fooFormatText()?
当前回答
我使用的另一种方法是: 1)在应用程序\FolderName\fileName.php中创建一个文件,并在其中包含以下代码
<?php
namespace App\library
{
class hrapplication{
public static function libData(){
return "Data";
}
}
}
?>
2)之后在我们的刀片
$FmyFunctions = new \App\FolderName\classsName;
echo $is_ok = ($FmyFunctions->libData());
就是这样。这是可行的
其他回答
在SO和谷歌上筛选了各种各样的答案后,我仍然没有找到一个最佳的方法。大多数答案建议我们离开应用程序,依靠第三方工具Composer来完成工作,但我不相信仅仅为了包含一个文件而耦合到一个工具是明智的。
Andrew Brown的回答最接近我认为应该如何处理它,但是(至少在5.1中),服务提供者步骤是不必要的。Heisian的回答强调了PSR-4的使用,这让我们更接近了一步。下面是视图中helper的最终实现:
首先,在你的app目录中创建一个helper文件,命名空间为:
namespace App\Helpers;
class BobFinder
{
static function bob()
{
return '<strong>Bob?! Is that you?!</strong>';
}
}
接下来,在config\app.php中,在aliases数组中为你的类添加别名:
'aliases' => [
// Other aliases
'BobFinder' => App\Helpers\BobFinder::class
]
这就是你需要做的。PSR-4和别名应该向你的视图公开helper,所以在你的视图中,如果你输入:
{!! BobFinder::bob() !!}
它应该输出:
<strong>Bob?! Is that you?!</strong>
在App/Helpers/中创建新文件examplehelper.php 然后加入作曲家。json文件
"autoload": { "classmap": [ "database"], "psr-4": { "App\\": "app/" },
"files": ["helpers/examplehelper.php" ]},
下面是我创建的一个bash shell脚本,用于快速制作Laravel 5外观。
在Laravel 5安装目录中运行这个程序。
这样叫它:
make_facade.sh -f <facade_name> -n '<namespace_prefix>'
例子:
make_facade.sh -f helper -n 'App\MyApp'
如果你运行这个例子,它会在“your_laravel_installation_dir/app/MyApp”下创建目录Facades和Providers。
它将创建以下3个文件,并将它们输出到屏幕上:
./app/MyApp/Facades/Helper.php
./app/MyApp/Facades/HelperFacade.php
./app/MyApp/Providers/HelperServiceProvider.php
完成后,它将显示类似于下面的消息:
===========================
Finished
===========================
Add these lines to config/app.php:
----------------------------------
Providers: App\MyApp\Providers\HelperServiceProvider,
Alias: 'Helper' => 'App\MyApp\Facades\HelperFacade',
更新'config/app.php'中的Providers和Alias列表
运行composer -o dumpautoload
"./app/MyApp/Facades/Helper.php"最初看起来是这样的:
<?php
namespace App\MyApp\Facades;
class Helper
{
//
}
现在只需在“。/app/MyApp/Facades/Helper.php”中添加方法。
下面是“。/app/MyApp/Facades/Helper.php”在我添加了一个Helper函数后的样子。
<?php
namespace App\MyApp\Facades;
use Request;
class Helper
{
public function isActive($pattern = null, $include_class = false)
{
return ((Request::is($pattern)) ? (($include_class) ? 'class="active"' : 'active' ) : '');
}
}
This is how it would be called:
===============================
{!! Helper::isActive('help', true) !!}
这个函数需要一个模式,并且可以接受可选的第二个布尔参数。
如果当前URL匹配传递给它的模式,它将输出'active'(或者'class="active"',如果你添加'true'作为函数调用的第二个参数)。
我用它来突出显示激活的菜单。
下面是我的脚本的源代码。我希望你觉得它有用,如果你有任何问题请告诉我。
#!/bin/bash
display_syntax(){
echo ""
echo " The Syntax is like this:"
echo " ========================"
echo " "$(basename $0)" -f <facade_name> -n '<namespace_prefix>'"
echo ""
echo " Example:"
echo " ========"
echo " "$(basename $0) -f test -n "'App\MyAppDirectory'"
echo ""
}
if [ $# -ne 4 ]
then
echo ""
display_syntax
exit
else
# Use > 0 to consume one or more arguments per pass in the loop (e.g.
# some arguments don't have a corresponding value to go with it such
# as in the --default example).
while [[ $# > 0 ]]
do
key="$1"
case $key in
-n|--namespace_prefix)
namespace_prefix_in="$2"
echo ""
shift # past argument
;;
-f|--facade)
facade_name_in="$2"
shift # past argument
;;
*)
# unknown option
;;
esac
shift # past argument or value
done
fi
echo Facade Name = ${facade_name_in}
echo Namespace Prefix = $(echo ${namespace_prefix_in} | sed -e 's#\\#\\\\#')
echo ""
}
function display_start_banner(){
echo '**********************************************************'
echo '* STARTING LARAVEL MAKE FACADE SCRIPT'
echo '**********************************************************'
}
# Init the Vars that I can in the beginning
function init_and_export_vars(){
echo
echo "INIT and EXPORT VARS"
echo "===================="
# Substitution Tokens:
#
# Tokens:
# {namespace_prefix}
# {namespace_prefix_lowerfirstchar}
# {facade_name_upcase}
# {facade_name_lowercase}
#
namespace_prefix=$(echo ${namespace_prefix_in} | sed -e 's#\\#\\\\#')
namespace_prefix_lowerfirstchar=$(echo ${namespace_prefix_in} | sed -e 's#\\#/#g' -e 's/^\(.\)/\l\1/g')
facade_name_upcase=$(echo ${facade_name_in} | sed -e 's/\b\(.\)/\u\1/')
facade_name_lowercase=$(echo ${facade_name_in} | awk '{print tolower($0)}')
# Filename: {facade_name_upcase}.php - SOURCE TEMPLATE
source_template='<?php
namespace {namespace_prefix}\Facades;
class {facade_name_upcase}
{
//
}
'
# Filename: {facade_name_upcase}ServiceProvider.php - SERVICE PROVIDER TEMPLATE
serviceProvider_template='<?php
namespace {namespace_prefix}\Providers;
use Illuminate\Support\ServiceProvider;
use App;
class {facade_name_upcase}ServiceProvider extends ServiceProvider {
public function boot()
{
//
}
public function register()
{
App::bind("{facade_name_lowercase}", function()
{
return new \{namespace_prefix}\Facades\{facade_name_upcase};
});
}
}
'
# {facade_name_upcase}Facade.php - FACADE TEMPLATE
facade_template='<?php
namespace {namespace_prefix}\Facades;
use Illuminate\Support\Facades\Facade;
class {facade_name_upcase}Facade extends Facade {
protected static function getFacadeAccessor() { return "{facade_name_lowercase}"; }
}
'
}
function checkDirectoryExists(){
if [ ! -d ${namespace_prefix_lowerfirstchar} ]
then
echo ""
echo "Can't find the namespace: "${namespace_prefix_in}
echo ""
echo "*** NOTE:"
echo " Make sure the namspace directory exists and"
echo " you use quotes around the namespace_prefix."
echo ""
display_syntax
exit
fi
}
function makeDirectories(){
echo "Make Directories"
echo "================"
mkdir -p ${namespace_prefix_lowerfirstchar}/Facades
mkdir -p ${namespace_prefix_lowerfirstchar}/Providers
mkdir -p ${namespace_prefix_lowerfirstchar}/Facades
}
function createSourceTemplate(){
source_template=$(echo "${source_template}" | sed -e 's/{namespace_prefix}/'${namespace_prefix}'/g' -e 's/{facade_name_upcase}/'${facade_name_upcase}'/g' -e 's/{facade_name_lowercase}/'${facade_name_lowercase}'/g')
echo "Create Source Template:"
echo "======================="
echo "${source_template}"
echo ""
echo "${source_template}" > ./${namespace_prefix_lowerfirstchar}/Facades/${facade_name_upcase}.php
}
function createServiceProviderTemplate(){
serviceProvider_template=$(echo "${serviceProvider_template}" | sed -e 's/{namespace_prefix}/'${namespace_prefix}'/g' -e 's/{facade_name_upcase}/'${facade_name_upcase}'/g' -e 's/{facade_name_lowercase}/'${facade_name_lowercase}'/g')
echo "Create ServiceProvider Template:"
echo "================================"
echo "${serviceProvider_template}"
echo ""
echo "${serviceProvider_template}" > ./${namespace_prefix_lowerfirstchar}/Providers/${facade_name_upcase}ServiceProvider.php
}
function createFacadeTemplate(){
facade_template=$(echo "${facade_template}" | sed -e 's/{namespace_prefix}/'${namespace_prefix}'/g' -e 's/{facade_name_upcase}/'${facade_name_upcase}'/g' -e 's/{facade_name_lowercase}/'${facade_name_lowercase}'/g')
echo "Create Facade Template:"
echo "======================="
echo "${facade_template}"
echo ""
echo "${facade_template}" > ./${namespace_prefix_lowerfirstchar}/Facades/${facade_name_upcase}Facade.php
}
function serviceProviderPrompt(){
echo "Providers: ${namespace_prefix_in}\Providers\\${facade_name_upcase}ServiceProvider,"
}
function aliasPrompt(){
echo "Alias: '"${facade_name_upcase}"' => '"${namespace_prefix_in}"\Facades\\${facade_name_upcase}Facade',"
}
#
# END FUNCTION DECLARATIONS
#
###########################
## START RUNNING SCRIPT ##
###########################
display_start_banner
init_and_export_vars
makeDirectories
checkDirectoryExists
echo ""
createSourceTemplate
createServiceProviderTemplate
createFacadeTemplate
echo ""
echo "==========================="
echo " Finished TEST"
echo "==========================="
echo ""
echo "Add these lines to config/app.php:"
echo "----------------------------------"
serviceProviderPrompt
aliasPrompt
echo ""
在dir bootstrap\autoload.php中
require __DIR__.'/../vendor/autoload.php';
require __DIR__.'/../app/Helpers/function.php'; //add
添加这个文件
app\Helpers\function.php
**
地位的助手
** 创建新助手
<?php
namespace App\Helpers;
use Illuminate\Database\Eloquent\Collection;
class StatusHelper
{
protected static $_status = [
1=> [
'value' => 1,
'displayName' => 'Active',
],
2 => [
'value' => 2,
'displayName' => 'Inactive',
],
3 => [
'value' => 3,
'displayName' => 'Delete',
],
];
public static function getStatusesList()
{
$status = (new Collection(self::$_status))->pluck('displayName', 'value')->toArray();
return $status;
}
}
用于控制器和任何视图文件
use App\Helpers\StatusHelper;
class ExampleController extends Controller
{
public function index()
{
$statusList = StatusHelper::getStatusesList();
return view('example.index', compact('statusList'));
}
}