laravel 自定义公共函数
创建 functions.php
在 app/Helpers/(目录可以自己随便来)下新建一个文件 functions.php,在内部补充如下代码:
<?php
/**
* Created by PhpStorm.
* User: fhl
* Date: 2018/4/13
* Time: 10:37
*/
/**
* 获取当前控制器与方法
* @return array
*/
if (!function_exists('getCurrentAction')) {
function getCurrentAction()
{
$action = \Route::current()->getActionName();
list($class, $method) = explode('@', $action);
$class = substr(strrchr($class, '\\'), 1);
return ['controller' => $class, 'method' => $method];
}
}
/**
* 获取当前控制器名
* @return string
*/
if (!function_exists('getCurrentControllerName')) {
function getCurrentControllerName()
{
return getCurrentAction()['controller'];
}
}
/**
* 获取当前方法名
* @return string
*/
if (!function_exists('getCurrentMethodName')) {
function getCurrentMethodName()
{
return getCurrentAction()['method'];
}
}
/**
* 生成随机字符串
* @param number $length
*/
function generateStr($count = 10, $rm_similar = 1)
{
$chars = array_flip(array_merge(range(0, 9), range('A', 'Z')));
if ($rm_similar) {
unset ($chars [0], $chars [1], $chars [2], $chars [5], $chars [8], $chars ['B'], $chars ['I'], $chars ['O'], $chars ['Q'], $chars ['S'], $chars ['U'], $chars ['V'], $chars ['Z']);
}
for ($i = 0, $text = ''; $i < $count; $i++) {
$text .= array_rand($chars);
}
return $text;
}
/**
* 验证邮箱格式
* @param $email
* @return bool
*/
function filterEmail($email)
{
$reg = "/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/";
return preg_match($reg, $email) ? true : false;
}
/**
* 验证手机号码格式
* @var string $phone
* @return boolean
*/
function filterCellPhone($phone)
{
if (!is_numeric($phone)) {
return false;
}
return preg_match('#^1[3,4,5,7,8][\d]{9}$#', $phone) ? true : false;
}
配置 composer.json
打开项目根目录下的 composer.json 文件,找到"autoload" 配置项,补充如下代码:
"autoload": {
"files": [
"app/Helpers/functions.php"
],
},
执行 composer 命令
打开终端,执行下面的命令:
composer dump-auto
测试
在控制器的随意一个方法中执行下面代码,有数据输出则配置成功:
if (!filterEmail('563315999@qq.com')) {
return 'email 有误!';
}