在Yii2框架中,更好地定义通用功能,这些功能在任何地方都可以访问,比如控制器、模型、视图
就像我想创建名为“dt()的函数” 并希望像这样访问它:-在Yii2框架中,更好地定义通用功能,这些功能在任何地方都可以访问,比如控制器、模型、视图,yii,yii2,yii2-advanced-app,yii2-basic-app,Yii,Yii2,Yii2 Advanced App,Yii2 Basic App,就像我想创建名为“dt()的函数” 并希望像这样访问它:- echo dt(); //retrun current date and time format 在Yi2框架中,哪个位置更适合这样做?您可以这样使用它: 创建一个文件夹/common/helpers/,然后在那里创建一个helper类并添加静态方法 namespace common\helpers; class DateHelper { public static function dt(){ retur
echo dt(); //retrun current date and time format
在Yi2框架中,哪个位置更适合这样做?您可以这样使用它:
创建一个文件夹/common/helpers/
,然后在那里创建一个helper类并添加静态方法
namespace common\helpers;
class DateHelper
{
public static function dt(){
return date('Y-m-d H:i:s');
}
}
用法
您可以这样使用它:
创建一个文件夹/common/helpers/
,然后在那里创建一个helper类并添加静态方法
namespace common\helpers;
class DateHelper
{
public static function dt(){
return date('Y-m-d H:i:s');
}
}
用法
这不是一个好方法,但是如果您坚持使用函数而不是静态类,那么可以将方法定义放在
bootstrap.php
中
通常,除了定义别名,我在bootstrap.php中放的是配置兼容性,例如在fastcgi中没有
getallheaders
,因此我在那里定义它。这不是一个好方法,但如果坚持使用函数而不是静态类,则可以将方法定义放在bootstrap.php
中
通常,除了定义别名,我在bootstrap.php中放的是配置兼容性,例如在fastcgi中没有
getallheaders
,因此我在那里定义它。对于Yi2,首先在项目根文件夹中创建一个名为“components”
的文件夹
然后在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();
对于yii2,首先在项目根文件夹中创建一个名为
“components”
的文件夹
然后在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();
我使用“通用/组件”文件夹。在这里,我创建了一个文件名“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;
}
}
我也对模特做同样的事情。我扩展了所有ActiveMDEL和模型[没有DB连接],当它们在验证后出现任何错误时,我会使用Yii::error()或Yii::info()或Yii::warning()在数据库中插入有关错误跟踪的数据
我做了很多事情使编码变得简单有趣,并不断学习新的东西 我使用“通用/组件”文件夹。在这里,我创建了一个文件名“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;
}
}
我也对模特做同样的事情。我扩展了所有ActiveMDEL和模型[没有DB连接],当它们在验证后出现任何错误时,我会使用Yii::error()或Yii::info()或Yii::warning()在数据库中插入有关错误跟踪的数据
我做了很多事情使编码变得简单有趣,并不断学习新的东西 我希望它对你有帮助我希望它对你有帮助我想实施这个解决方案。这是一个更好的解决方案<代码>:)我想为我实现这个解决方案。这是一个更好的解决方案<代码>:)