I have a helper which change different strings to dates. By this +5 becomes 2012-11-17 (5 days from today), 5 becomes 2012-11-05 (this year, this month, given day).
I would like to use the same thing in my controller.
App::uses('EasyDateHelper', 'View/Helper');
App::uses('View', 'View');
$this->View = new View($this->Controller);
$easyDate = new EasyDateHelper($this->View);
This code works well, but i would like to know if there is a better / simpler way to do.
Yeah, there is. Don't make it a helper!
Helpers are by design only for the view level. If you need it in a controller, your design is wrong.
So make it a lib class etc and use it in your controllers this way. and either use the same lib in your helpers or make a wrapper helper (similar to TextHelper for String, NumberHelper for CakeNumber, TimeHelper for CakeTime etc) to easily access the methods in your view scope.
For more complex solutions take a look at Sessions:
CakeSession is the lib class.
SessionComponent wraps it for the controller layer
SessionHelper wraps it for the view layer
For a Lib "DateLib" (you can name it whatever you like as long as the class name is unique throughout app and core): Either put it in /Lib/ or /Lib/PackageName whereas PackageName can be defined by you (e.g. "Utility"). It is better to group by PackageName instead of putting it in Lib directly.
/Lib/Utility/DateLib.php
And in your code:
App::uses('DateLib', 'Utility');
$date = DateLib::format(); // for static methods
$DateLib = new DateLib();
$date = $DateLib->format(); // creating an extra object here
if you can work with static methods you should. this is also the way cake does it for the CakeTime, CakeNumber and String classes (see the code for details).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With