在 Yii2 框架中,更好的地方定义可以随处访问的通用功能,如控制器、模型、视图
In Yii2 framework, better place to define common function which is accessible everywhere like controller, model, view
就像我想创建名称为 "dt()"
的函数
function dt(){
return date('Y-m-d H:i:s');
}
并想像这样访问它:-
echo dt(); //retrun current date and time format
在 Yii2 框架中哪个地方更适合这样做?
你可以这样使用它:http://www.yiiframework.com/extension/yii2-helpers/
创建一个文件夹 /common/helpers/
,然后在那里创建一个助手 class 并添加您的静态方法。
namespace common\helpers;
class DateHelper
{
public static function dt(){
return date('Y-m-d H:i:s');
}
}
用法
use common\helpers\DateHelper;
echo DateHelper::dt();
这不是一个好方法,但如果你坚持使用函数而不是静态 class,你可以将方法定义放在 bootstrap.php
.
通常我在bootstrap.php中除了定义别名外就是配置兼容性,例如在fastcgi中没有getallheaders
,所以我在那里定义它。
对于 yii2,首先在项目根文件夹中创建一个名为 "components"
的文件夹。
然后在组件文件夹中编写您的自定义组件。即 MyComponent.php
或任何内容。
namespace app\components;
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
class MyComponent extends Component
{
public function dt(){
return date('Y-m-d H:i:s');
}
}
现在将您的组件添加到配置文件中。
'components' => [
'mycomponent' => [
'class' => 'app\components\MyComponent',
],
]
大功告成!现在您可以在任何控制器、模型或视图中使用您的组件函数 "dt"..
例如:
Yii::$app->MyComponent->dt();
我使用 "common/components" 文件夹。在这里,我创建了一个文件名 "AppBasic.php",它将具有 PHP 的功能以及 Yii 相关的功能。
部分功能..
namespace common\components;
//Please make use of other classes you will use.
use yii\base\Exception;
use Yii;
/**
* Class AppBasic Provides basic function to make programming EASY and FUN things
* Author : Jaimin MosLake
**/
class AppBasic
{
/*
* I use this function to handle auto complete of password
* I put this in start of login page so chrome/ other browsers do not auto complete the username and password.
*/
public static function renderAutoCompleteOff()
{
return '
<input type="text" style="visibility: hidden;height:0px;" />
<input type="password" style="visibility: hidden;height:0px;" />';
}
/*
* My all time favorite checks whether it is array or not , if it is it returns value.
*/
public static function arrayKeyExist($key, $array , $returnValue = 1, $returnArray = 0)
{
if($returnValue)
{
return is_array($array) ? array_key_exists($key , $array) ? $array[$key] : ( $returnArray ? [] : null ) : ( $returnArray ? [] : null ) ;
}
else
{
return is_array($array) ? array_key_exists($key , $array) ? true : false : false ;
}
}
public static function arrayNotEmpty( $array )
{
return is_array($array) ? !empty($array) ? true : false : false ;
}
public static function propertyExist($key, $object , $returnValue = 1)
{
if($returnValue)
{
return is_object($object) ? property_exists($object , $key) ? $object->$key : null : null ;
}
else
{
return is_object($object) ? property_exists($object , $key) ? 1 : 0 : 0 ;
}
}
public static function isSquential($arr)
{
return is_array($arr) ? array_keys($arr) === range(0, count($arr) - 1) : 0;
}
public static function makeItSquential($arr)
{
return (!empty($arr)) ? (self::isSquential($arr) ? $arr : [$arr]) : [] ;
}
public static function stringNotNull($string)
{
return ($string != "" && $string != null);
}
public static function giveDetail($data)
{
return (is_object($data) ? "OBJECT" : (is_array($data) ? (AppBasic::isSquential($data) ? "SEQUENTIAL_ARRAY" : "ASSOCIATIVE_ARRAY" ) : "STRING" )) ;
}
public static function printR($data, $exit = 1)
{
echo "<pre></br>";
print_r($data);
if ($exit == '1') {
exit;
}
echo "</pre></br>";
}
public static function printRT($data, $title = null , $exit = 0)
{
AppBasic::printR($title." START ", 0);
AppBasic::printR($data, 0 );
AppBasic::printR($title." END ", $exit);
}
public static function test($exit = 0 , $file = __FILE__, $class = __CLASS__ , $function = __FUNCTION__, $line = __LINE__ )
{
self::printR(" FILE : ".$file." <br/> CLASS : ".$class." <BR/> FUNCTION : ".$function." <BR/> LINE : ".$line, $exit);
}
public static function printReturn($data, $status = 1)
{
$html = "" ;
$html .= "<pre></br>";
$html .= print_r($data , true );
$html .= "</pre></br>";
return $html ;
}
public static function getErrorArray($msg, $errors)
{
foreach ($errors as $k => $value)
{
for ($i = 0; $i < sizeof($value); $i++)
{
$msg[sizeof($msg)] = $value[$i];
}
}
return $msg;
}
public static function getErrorArrayStraight($msg, $errors)
{
foreach ($msg as $k => $value) {
$p = array_key_exists($k, $errors) ? sizeof($errors[$k]) : 0;
$errors[$k][$p] = $value;
}
return $errors;
}
public static function getFinalError($array1, $array2)
{
$error = Helpers::getErrorArrayStraight($array1, $array2);
$message = Helpers::getErrorMessageStraight($error);
return $message;
}
public static function getErrorMessageStraight($errors)
{
$html = "";
$html .= "<p>Please solve the following errors</p>";
$html .= "<ul>";
foreach ($errors as $k => $value) {
for ($i = 0; $i < sizeof($value); $i++) {
$html .= "<li>";
$html .= $value[$i];
$html .= "</li>";
}
}
$html .= "</ul>";
return $html;
}
public static function getErrorMessage($type, $msg)
{
$html = "";
if ($type == "failed") {
$html .= '<div class="whistleblower" >--__FAILED__--</div>';
$html .= '<div class="errors"><ul id="errors">';
for ($i = 0; $i < sizeof($msg); $i++) {
$html .= '<li>' . $msg[$i] . '</li>';
}
$html .= '</ul></div>';
} else {
$html .= '<div class="whistleblower" >--__SUCCESS__--</div>';
$html .= '<div class="errors"><ul id="errors">';
for ($i = 0; $i < sizeof($msg); $i++) {
$html .= '<li>' . $msg[$i] . '</li>';
}
$html .= '</ul></div>';
}
return $html;
}
public static function getUrlInfo($name , $operator = "/")
{
$controllerName = \Yii::$app->controller->id ;
$controllerName = strtolower($controllerName) ;
$actionName = \Yii::$app->controller->action->id ;
$actionName = strtolower($actionName) ;
$combination = $controllerName.$operator.$actionName ;
return $$name ;
}
public static function date_convert($dt, $tz1, $df1 = "Y-m-d H:i:s", $tz2 = "UTC", $df2 = "Y-m-d H:i:s")
{
$returnVal = null ;
if($dt != null || $dt != "")
{
if($tz1 == null || $tz1 == "")
{
$tz1 = date_default_timezone_get();
}
if($tz2 == null || $tz2 == "")
{
$tz2 = "UTC";
}
$timeZoneObj = new DateTimeZone($tz1);
//create DateTime object
$d = DateTime::createFromFormat($df1, $dt, $timeZoneObj );
//convert timezone
if(is_object($d))
{
$timeZoneObj2 = new DateTimeZone($tz2);
try
{
$d->setTimeZone($timeZoneObj2);
}
catch(Exception $e)
{
throw new Exception("Date can not be formatted");
}
}
//convert dateformat
$returnVal = is_object($d) ? $d->format($df2) : null ;
}
return $returnVal ;
}
public static function checkValidations($model, $exit = 1)
{
self::printR('Attribute', 0);
self::printR($model->scenario, 0);
self::printR('Attribute', 0);
self::printR($model->attributes, 0);
self::printR('Validate', 0);
self::printR($model->validate(), 0);
self::printR('Errors', 0);
self::printR($model->getErrors(), 0);
//self::printR('Model', 0);
//self::printR($model, 0);
if ($exit) {
exit;
}
}
public static function setTimeZoneByTimezone($tz)
{
if($tz != null && $tz != "")
{
//Helpers::printR($tz );
ini_set('date.timezone', $tz);
//echo date_default_timezone_get();
//exit;
}
}
public static function generateRandomString($length = 10)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
public static function getExtention($filename)
{
$ext = pathinfo($filename, PATHINFO_EXTENSION);
return $ext;
}
public static function createDirectoryStructureFromBasePath($structure)
{
$url = Yii::app()->basePath;
$explode = explode("/", $structure);
//self::printR($explode , 0 );
foreach($explode as $k=>$val)
{
if($val == "..")
{
$dir = $url."/".$val;
if(file_exists($dir) && is_dir($dir))
{
$url = $dir ;
}
else
{
$url = $url ;
}
}
else if($val != "")
{
$dir = $url.'/'.$val;
if (!file_exists($dir) && !is_dir($dir)) {
mkdir($dir);
}
$url = $dir ;
}
}
return $url."/" ;
//self::printR($url);
//$file = $dir."/".$fileNameShould;
}
}
我也为控制器做同样的事情。我通过 Backendcontroller 和 FrontendController 扩展它们。它们由 MosLakeController [我的名字] 扩展,并由控制器扩展。
所以我把所有的访问控制都放到了前端和后端控制器中。我在 MosLakeController 中也有功能。
public function handleRender($view , $params = [] , $jsonBasedRender = 0 , $jsonBasedRenderOptions = [] , $returnHtml = 0 , $renderPartial = 0 )
{
if(\Yii::$app->request->isAjax)
{
if($returnHtml)
{
return $this->renderPartial($view , $params);
}
else if($jsonBasedRender)
{
$html = $this->renderPartial($view , $params);
$jsonBasedRenderOptions['html'] = $html ;
$jsonBasedRenderOptions['status'] = 1 ;
$jsonBasedRenderOptions['action'] = isset($jsonBasedRenderOptions['action']) ? $jsonBasedRenderOptions['action'] : "RENDER" ;
$jsonBasedRenderOptions['message'] = isset($jsonBasedRenderOptions['message']) ? $jsonBasedRenderOptions['message'] : "" ;
echo json_encode($jsonBasedRenderOptions);
exit;
}
else
{
return $this->renderPartial($view , $params);
}
}
else if($renderPartial)
{
return $this->renderPartial($view, $params);
}
else
{
return $this->render($view, $params);
}
}
public function findModelByPk($modelName , $primaryKey, $strict = 1)
{
$model = new $modelName();
if($primaryKey != '')
{
$model = $model->findOne($primaryKey);
}
if($model == null && $strict == 1)
{
throw new Exception('Required data is not exist.');
}
return $model;
}
public function findModelByAttributes($modelName, $condition, $params, $strict = 1, $one = 1)
{
$model = new $modelName();
if($one)
{
$model = $model->find()->where($condition , $params )->one();
if($model == null && $strict == 1)
{
throw new HttpException('Required data is not exist for '.$modelName.'.');
}
else if($model == null)
{
$model = new $modelName();
}
}
else
{
$model = $model->find()->where($condition , $params )->all();
if(empty($model) && $strict == 1)
{
throw new HttpException('Required data is not exist for '.$modelName.'.');
}
else if(empty($model))
{
$model = [new $modelName()];
}
}
return $model;
}
我也为模特做同样的事情。我扩展了所有 ActiveMdels 和 ALso 模型 [没有数据库连接],当它们在验证后有任何错误时,我在数据库中插入有关错误跟踪的数据 Yii::error() 或 Yii::info() 或 Yii::warning().
我做了很多事情来使编码变得简单有趣并不断学习新事物..!!!
就像我想创建名称为 "dt()"
的函数function dt(){
return date('Y-m-d H:i:s');
}
并想像这样访问它:-
echo dt(); //retrun current date and time format
在 Yii2 框架中哪个地方更适合这样做?
你可以这样使用它:http://www.yiiframework.com/extension/yii2-helpers/
创建一个文件夹 /common/helpers/
,然后在那里创建一个助手 class 并添加您的静态方法。
namespace common\helpers;
class DateHelper
{
public static function dt(){
return date('Y-m-d H:i:s');
}
}
用法
use common\helpers\DateHelper;
echo DateHelper::dt();
这不是一个好方法,但如果你坚持使用函数而不是静态 class,你可以将方法定义放在 bootstrap.php
.
通常我在bootstrap.php中除了定义别名外就是配置兼容性,例如在fastcgi中没有getallheaders
,所以我在那里定义它。
对于 yii2,首先在项目根文件夹中创建一个名为 "components"
的文件夹。
然后在组件文件夹中编写您的自定义组件。即 MyComponent.php
或任何内容。
namespace app\components;
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
class MyComponent extends Component
{
public function dt(){
return date('Y-m-d H:i:s');
}
}
现在将您的组件添加到配置文件中。
'components' => [
'mycomponent' => [
'class' => 'app\components\MyComponent',
],
]
大功告成!现在您可以在任何控制器、模型或视图中使用您的组件函数 "dt"..
例如:
Yii::$app->MyComponent->dt();
我使用 "common/components" 文件夹。在这里,我创建了一个文件名 "AppBasic.php",它将具有 PHP 的功能以及 Yii 相关的功能。
部分功能..
namespace common\components;
//Please make use of other classes you will use.
use yii\base\Exception;
use Yii;
/**
* Class AppBasic Provides basic function to make programming EASY and FUN things
* Author : Jaimin MosLake
**/
class AppBasic
{
/*
* I use this function to handle auto complete of password
* I put this in start of login page so chrome/ other browsers do not auto complete the username and password.
*/
public static function renderAutoCompleteOff()
{
return '
<input type="text" style="visibility: hidden;height:0px;" />
<input type="password" style="visibility: hidden;height:0px;" />';
}
/*
* My all time favorite checks whether it is array or not , if it is it returns value.
*/
public static function arrayKeyExist($key, $array , $returnValue = 1, $returnArray = 0)
{
if($returnValue)
{
return is_array($array) ? array_key_exists($key , $array) ? $array[$key] : ( $returnArray ? [] : null ) : ( $returnArray ? [] : null ) ;
}
else
{
return is_array($array) ? array_key_exists($key , $array) ? true : false : false ;
}
}
public static function arrayNotEmpty( $array )
{
return is_array($array) ? !empty($array) ? true : false : false ;
}
public static function propertyExist($key, $object , $returnValue = 1)
{
if($returnValue)
{
return is_object($object) ? property_exists($object , $key) ? $object->$key : null : null ;
}
else
{
return is_object($object) ? property_exists($object , $key) ? 1 : 0 : 0 ;
}
}
public static function isSquential($arr)
{
return is_array($arr) ? array_keys($arr) === range(0, count($arr) - 1) : 0;
}
public static function makeItSquential($arr)
{
return (!empty($arr)) ? (self::isSquential($arr) ? $arr : [$arr]) : [] ;
}
public static function stringNotNull($string)
{
return ($string != "" && $string != null);
}
public static function giveDetail($data)
{
return (is_object($data) ? "OBJECT" : (is_array($data) ? (AppBasic::isSquential($data) ? "SEQUENTIAL_ARRAY" : "ASSOCIATIVE_ARRAY" ) : "STRING" )) ;
}
public static function printR($data, $exit = 1)
{
echo "<pre></br>";
print_r($data);
if ($exit == '1') {
exit;
}
echo "</pre></br>";
}
public static function printRT($data, $title = null , $exit = 0)
{
AppBasic::printR($title." START ", 0);
AppBasic::printR($data, 0 );
AppBasic::printR($title." END ", $exit);
}
public static function test($exit = 0 , $file = __FILE__, $class = __CLASS__ , $function = __FUNCTION__, $line = __LINE__ )
{
self::printR(" FILE : ".$file." <br/> CLASS : ".$class." <BR/> FUNCTION : ".$function." <BR/> LINE : ".$line, $exit);
}
public static function printReturn($data, $status = 1)
{
$html = "" ;
$html .= "<pre></br>";
$html .= print_r($data , true );
$html .= "</pre></br>";
return $html ;
}
public static function getErrorArray($msg, $errors)
{
foreach ($errors as $k => $value)
{
for ($i = 0; $i < sizeof($value); $i++)
{
$msg[sizeof($msg)] = $value[$i];
}
}
return $msg;
}
public static function getErrorArrayStraight($msg, $errors)
{
foreach ($msg as $k => $value) {
$p = array_key_exists($k, $errors) ? sizeof($errors[$k]) : 0;
$errors[$k][$p] = $value;
}
return $errors;
}
public static function getFinalError($array1, $array2)
{
$error = Helpers::getErrorArrayStraight($array1, $array2);
$message = Helpers::getErrorMessageStraight($error);
return $message;
}
public static function getErrorMessageStraight($errors)
{
$html = "";
$html .= "<p>Please solve the following errors</p>";
$html .= "<ul>";
foreach ($errors as $k => $value) {
for ($i = 0; $i < sizeof($value); $i++) {
$html .= "<li>";
$html .= $value[$i];
$html .= "</li>";
}
}
$html .= "</ul>";
return $html;
}
public static function getErrorMessage($type, $msg)
{
$html = "";
if ($type == "failed") {
$html .= '<div class="whistleblower" >--__FAILED__--</div>';
$html .= '<div class="errors"><ul id="errors">';
for ($i = 0; $i < sizeof($msg); $i++) {
$html .= '<li>' . $msg[$i] . '</li>';
}
$html .= '</ul></div>';
} else {
$html .= '<div class="whistleblower" >--__SUCCESS__--</div>';
$html .= '<div class="errors"><ul id="errors">';
for ($i = 0; $i < sizeof($msg); $i++) {
$html .= '<li>' . $msg[$i] . '</li>';
}
$html .= '</ul></div>';
}
return $html;
}
public static function getUrlInfo($name , $operator = "/")
{
$controllerName = \Yii::$app->controller->id ;
$controllerName = strtolower($controllerName) ;
$actionName = \Yii::$app->controller->action->id ;
$actionName = strtolower($actionName) ;
$combination = $controllerName.$operator.$actionName ;
return $$name ;
}
public static function date_convert($dt, $tz1, $df1 = "Y-m-d H:i:s", $tz2 = "UTC", $df2 = "Y-m-d H:i:s")
{
$returnVal = null ;
if($dt != null || $dt != "")
{
if($tz1 == null || $tz1 == "")
{
$tz1 = date_default_timezone_get();
}
if($tz2 == null || $tz2 == "")
{
$tz2 = "UTC";
}
$timeZoneObj = new DateTimeZone($tz1);
//create DateTime object
$d = DateTime::createFromFormat($df1, $dt, $timeZoneObj );
//convert timezone
if(is_object($d))
{
$timeZoneObj2 = new DateTimeZone($tz2);
try
{
$d->setTimeZone($timeZoneObj2);
}
catch(Exception $e)
{
throw new Exception("Date can not be formatted");
}
}
//convert dateformat
$returnVal = is_object($d) ? $d->format($df2) : null ;
}
return $returnVal ;
}
public static function checkValidations($model, $exit = 1)
{
self::printR('Attribute', 0);
self::printR($model->scenario, 0);
self::printR('Attribute', 0);
self::printR($model->attributes, 0);
self::printR('Validate', 0);
self::printR($model->validate(), 0);
self::printR('Errors', 0);
self::printR($model->getErrors(), 0);
//self::printR('Model', 0);
//self::printR($model, 0);
if ($exit) {
exit;
}
}
public static function setTimeZoneByTimezone($tz)
{
if($tz != null && $tz != "")
{
//Helpers::printR($tz );
ini_set('date.timezone', $tz);
//echo date_default_timezone_get();
//exit;
}
}
public static function generateRandomString($length = 10)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
public static function getExtention($filename)
{
$ext = pathinfo($filename, PATHINFO_EXTENSION);
return $ext;
}
public static function createDirectoryStructureFromBasePath($structure)
{
$url = Yii::app()->basePath;
$explode = explode("/", $structure);
//self::printR($explode , 0 );
foreach($explode as $k=>$val)
{
if($val == "..")
{
$dir = $url."/".$val;
if(file_exists($dir) && is_dir($dir))
{
$url = $dir ;
}
else
{
$url = $url ;
}
}
else if($val != "")
{
$dir = $url.'/'.$val;
if (!file_exists($dir) && !is_dir($dir)) {
mkdir($dir);
}
$url = $dir ;
}
}
return $url."/" ;
//self::printR($url);
//$file = $dir."/".$fileNameShould;
}
}
我也为控制器做同样的事情。我通过 Backendcontroller 和 FrontendController 扩展它们。它们由 MosLakeController [我的名字] 扩展,并由控制器扩展。
所以我把所有的访问控制都放到了前端和后端控制器中。我在 MosLakeController 中也有功能。
public function handleRender($view , $params = [] , $jsonBasedRender = 0 , $jsonBasedRenderOptions = [] , $returnHtml = 0 , $renderPartial = 0 )
{
if(\Yii::$app->request->isAjax)
{
if($returnHtml)
{
return $this->renderPartial($view , $params);
}
else if($jsonBasedRender)
{
$html = $this->renderPartial($view , $params);
$jsonBasedRenderOptions['html'] = $html ;
$jsonBasedRenderOptions['status'] = 1 ;
$jsonBasedRenderOptions['action'] = isset($jsonBasedRenderOptions['action']) ? $jsonBasedRenderOptions['action'] : "RENDER" ;
$jsonBasedRenderOptions['message'] = isset($jsonBasedRenderOptions['message']) ? $jsonBasedRenderOptions['message'] : "" ;
echo json_encode($jsonBasedRenderOptions);
exit;
}
else
{
return $this->renderPartial($view , $params);
}
}
else if($renderPartial)
{
return $this->renderPartial($view, $params);
}
else
{
return $this->render($view, $params);
}
}
public function findModelByPk($modelName , $primaryKey, $strict = 1)
{
$model = new $modelName();
if($primaryKey != '')
{
$model = $model->findOne($primaryKey);
}
if($model == null && $strict == 1)
{
throw new Exception('Required data is not exist.');
}
return $model;
}
public function findModelByAttributes($modelName, $condition, $params, $strict = 1, $one = 1)
{
$model = new $modelName();
if($one)
{
$model = $model->find()->where($condition , $params )->one();
if($model == null && $strict == 1)
{
throw new HttpException('Required data is not exist for '.$modelName.'.');
}
else if($model == null)
{
$model = new $modelName();
}
}
else
{
$model = $model->find()->where($condition , $params )->all();
if(empty($model) && $strict == 1)
{
throw new HttpException('Required data is not exist for '.$modelName.'.');
}
else if(empty($model))
{
$model = [new $modelName()];
}
}
return $model;
}
我也为模特做同样的事情。我扩展了所有 ActiveMdels 和 ALso 模型 [没有数据库连接],当它们在验证后有任何错误时,我在数据库中插入有关错误跟踪的数据 Yii::error() 或 Yii::info() 或 Yii::warning().
我做了很多事情来使编码变得简单有趣并不断学习新事物..!!!