Like i want to create function with name "dt()"
function dt(){
return date('Y-m-d H:i:s');
}
and want to access it like this:-
echo dt(); //retrun current date and time format
Which is better place in Yii2 framework to do that?
Like i want to create function with name "dt()"
function dt(){
return date('Y-m-d H:i:s');
}
and want to access it like this:-
echo dt(); //retrun current date and time format
Which is better place in Yii2 framework to do that?
You can use it this way: http://www.yiiframework.com/extension/yii2-helpers/
Create a folder /common/helpers/
, then create a helper class there and add your static methods.
namespace common\helpers;
class DateHelper
{
public static function dt(){
return date('Y-m-d H:i:s');
}
}
Usage
use common\helpers\DateHelper;
echo DateHelper::dt();
For yii2, First Make a folder named "components"
in your project root folder.
Then write your custom component inside components folder .i.e MyComponent.php
or anything.
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');
}
}
Now add your component inside the config file.
'components' => [
'mycomponent' => [
'class' => 'app\components\MyComponent',
],
]
You are done!. Now you can use your component function "dt" inside any of your controller, model or view..
For example:
Yii::$app->MyComponent->dt();
I use "common/components" folder. Here i create a file name "AppBasic.php" which will have functions which are for PHP and also Yii related functions.
some of the functions..
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;
}
}
I also do the same for controllers. I extend them by the Backendcontroller and FrontendController . They were extended by MosLakeController [My Name] and it is extended by controller.
So i put all access control thing into frontend and backend controller. I also have functions in 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;
}
And i also do the same for models. I extend all the ActiveMdels and ALso Models [ Without DB connection] and when theyhave any error afterValidate then i insert data in Database about the error trace with Yii::error() or Yii::info() or Yii::warning().
I do many things to make coding easy and fun and keep learning new things..!!!
It's not a good approach, but if you insists on having function instead of static class, you can put the method definition in bootstrap.php
.
Usually what I put in bootstrap.php other than defining alias is configuring compability, e.g in fastcgi there is no getallheaders
, hence I define it there.