creating a yii2 utiltiy function class ( SOLVED )

I am trying to create a utility class that will hold a lot of special formating functions

that I need all through my application. I did a search and found a lot of yii v1 topics,

but they did not work right.

Here is what I came up with, but it is not working…

I have a file at basic/components/utility/Datetime.php that contains:




<?php


namespace components\utility;


class Datetime

{

	public static function gettime( $datetime )

	{

		// process time field

		return( $time );

	}

	

	public static function getdate( $datetime )

	{

		// process date field...

		return( $date );

	}

}




In controller I have




use components\utility\Datetime;



Then in a controller action I try calling




	$date = Datetime::getdate( $datetime );



and it blows up with

Class 'components&#092;utility&#092;Datetime' not found

if you component folder are in base app directory maybe you can try this :


namespace app\components\utility;

else, read autoloading or Controllers Struture

OK, I was on the right track, I just did not have all the parts connected correctly…

So, for a utility class I created a php file on the path basic/components/Utility/DateTime.php

In this file I have the following code




<?php


namespace app\components\utility;


class Datetime

{

	

	public static function gettime( $datetime )

	{

		return( $time );

	}

	

	public static function getdate( $datetime )

	{

		return( $date );

	}

}

?>



Then in a controller ( or view… I think… ) I put a ‘use’ statement at the top of the file




use app\components\Utility\Datetime;



Then I can call the functions in the utility classes by something like:




$date = Datetime::getdate( $datetime );


$time = Datetime::putdate( $date );



The key thing I was missing was how to correctly specify the namespace, and getting all the capitalization correct.

To create additional utility class files, just duplicate the Datetime file and change all references to Datetime to the new classname you are using. Be sure to keep the capitalization the same.

Hope this helps others

-John