Reputation: 536
I am trying to create a custom class that can be called to convert dates and times for MySQL.
I am using the Yii2 Basic template
I have created a folder and a file in components called Convert.php
<?
namespace app\components;
use Yii;
class Convert
{
const DATE_FORMAT = 'php:Y-m-d';
const DATETIME_FORMAT = 'php:Y-m-d H:i:s';
const TIME_FORMAT = 'php:H:i:s';
public static function toMysql($dateStr, $type='date', $format = null) {
if ($type === 'datetime') {
$fmt = ($format == null) ? self::DATETIME_FORMAT : $format;
}
elseif ($type === 'time') {
$fmt = ($format == null) ? self::TIME_FORMAT : $format;
}
else {
$fmt = ($format == null) ? self::DATE_FORMAT : $format;
}
return \Yii::$app->formatter->asDate($dateStr, $fmt);
}
}
?>
I then try and call this method in my controller
use app\components\Convert;
...
public function actionCreate()
{
...
$model->date_of_birth = Convert::toMysql($model->date_of_birth);
...
}
However I am getting the following error
Unable to find 'app\components\Convert' in file: /var/www/html/portal/components/Convert.php. Namespace missing?
I am probably missing something simple, but I cannot see it.
Thanks for your help.
Liam
From the comments, I have found that the error was a simple mistake, the opening tag should have been
<?php
Upvotes: 3
Views: 2577
Reputation: 25302
This error simply means php cannot find the namespace in this file, and since the namespace seems to be correct, it is probably a php opening tag error.
Depending on your server php configuration, short open tags could be disabled, you should always use <?php
.
Upvotes: 1
Reputation:
You need to extend base Component from Yii2:
<?php
namespace app\components;
use yii\base\Component;
use Yii;
class Convert extends Component
{
const DATE_FORMAT = 'php:Y-m-d';
And then put in config/web.php
'components' => [
'convert' => [
'class' => 'app\components\Convert',
],
]
and access it as
$model->date_of_birth = Yii::$app->convert->toMysql($model->date_of_birth);
Upvotes: 1