How to define constructor ?Where? - yii

How to define constructor in Yii application?
Where ?to define the constructors?
I need to create constructors. Where it defines inside model or controller.
Can you guys give some example of formats ?

In a lot of Yii classes there are 2 methods that can be used to define initialization code : __construct() and init():
__construct() is a native php method to instantiate the object.
init() is called when Yii has performed it's own instantiation of the class (for example in a CActiveRecord class Yii has set the scenario name)
it's up to you to use
public function __construct()
{
//Your code
return parent::contruct()
}
or just to use the init method
public function init()
{
//Your code
}
if you use construct be carefull because some classes constructors have some params that you'll also have to set (for example CActiveRecord take the scenario name as a param)
If I were you I'll use the init method as often as possible.

Related

Factory method empty object

I have a factory method class that returns a cache system class (pseudo code):
class CacheFactory
{
public static function get($type) {
switch ($type) {
case 'memcache':
return new Memcache();
case 'redis':
return new Redis();
case 'default':
return new Void();
}
}
}
The cache classes implements simple get() and set() methods (it uses an abstract class defining the common methods) that allows me to easily switch cache systems if needed. The normal use will be like:
$cache = CacheFactory::get('redis');
$value = $cache->get('key');
...etc
I want to have a setting to enable/disable the cache, but I don't want to add conditionals in the code asking if the cache is enabled or not everywhere. So I was thinking in returning a Void() object that implements the abstract class methods so it will be used when the cache is disabled, the class will look like this:
class Void extends ACache
{
public function get(){};
public function set(){};
}
Would this be a good approach? How would you think will be the best way to handle the enabled/disabled setting without adding conditionals in the actual implementation?
Thanks!

Phalcon Initialize() is not working

I have 2 Controllers, TEST1Controller and TEST2Controller
In TEST2Controller I have a initialize() function setting value of a property.
If I try to access TEST2Controller directly from the browser, everything works perfectly.
But when I call a TEST2Controller method from TEST1Controller, it seems that initialize() function is not being called in TEST2Controller.
TEST1Controller:
namespace Modcont\Controller;
use Modcont\Controller\Test2Controller;
class Test1Controller extends BaseController
{
function gettestAction()
{
$t = new Test2Controller(); // calling TEST2 Controller Method Within TEST1 Controller
echo $t->dotestAction(" MYAPP ");
}
}
TEST2Controller:
namespace Modcont\Controller;
class Test2Controller extends BaseController
{
public $prefix;
function initialize()
{
$this->prefix = 'your name is';
}
function dotestAction($name)
{
return $this->prefix.' : '.$name;
}
}
Phalcon offers two ways for controller initialization, thy are the initialize and onContruct methods. The basic difference between these two methods is that initialize is called only when a controller is created by the framework to proceed with the execution of an action. Since you instantiating a controller object ad-hoc, initialize will not be called, only onConstruct will. So you'll need to put your initialization logic there:
function onConstruct()
{
$this->prefix = 'your name is';
}
Also, implementing native constructors in controller is discouraged, but if you do so, make sure to call the parent constructor in your own constructor: parent::__construct();.
All this information can be found in the Docs.

Base class for common YII functions?

I know how to create a class the will allow me to instantiate it and use across my project. What I want to be able to do is have functions without instantiating classes. For example, I know how to do this:
$core = new core();
$val = $core->convertToMyNotation($anotherval);
But what I want is to be able to do this ANYWHERE in any view, class whatever:
$val = convertToMyNotation($anotherval);
Where would I place these functions in order to be able to do that?
best way to do it, create a public function in components/Controller.php
public function globalFunction(){
// do something here.
}
and access it anywhere by
$this->globalFunction();
You can define a static method as an option.
class core{
public static function convertToMyNotation($value){
//do whatever here
return $value;
}
}
Then call it like so:
$val = core::convertToMyNotation($anotherval);
This requires no instantiation of the object to use. The only restriction is that you cannot use the $this property inside a static method.
Alternately, just define a file with your functions in it and include the file at some point early like, like within the boostrap script in your public_html/index.php file.
Edit: darkheir makes some good suggestions. Include such a class in your protected/components folder, and have it extend CComponent to gain some potentially useful enhancements.
By including the class in the protected/components folder, you gain the advantage of autoloading the class, by default.
There is no definitive question of your answer, it depends a lot on what the function will be doing!
If the function is performing some things specific to a model
(getting the last users, ...) this has to be in the User model as
Willem Renzema described:
class theModelClass {
public static function convertToMyNotation($value){
//do whatever here
return $value;
}
}
And you'll call it like
$val = theModelClass::convertToMyNotation($anotherval);
If the function is handling user inputs (sanitizing he inputs,
checking the values, ...) then it has to go to the controller and
you'll use Hemc solution:
Create a public function in components/Controller.php
public function globalFunction(){
// do something here.
}
and access it anywhere by
$this->globalFunction();
If the function is an Helper: performing some actions that do not
depend on models or user inoput then you can create a new class that
you'll put in your component directory:
class core extends CComponent{
public static function convertToMyNotation($value){
//do whatever here
return $value;
}
}
And
$val = core::convertToMyNotation($anotherval);
Actually, I think you're looking for this answer instead:
http://www.yiiframework.com/wiki/31/use-shortcut-functions-to-reduce-typing/
In essence, in your entry script, before you load up Yii, include a global functions file:
require('path/to/globals.php');
Then, any function defined in that file can be used as a shortcut. Be careful, but enjoy the power! :-)
Create something like
Class Core extends CApplicationComponent{
public function doSomething(){}
}
and in config main.php
'components'=>array(
'core'=>array(
'class' => 'Core'
),
),
and now you can call whenever you want
Yii::app()->core->doSomething();

OOP used in FuelPHP

I'm trying to undestand how FuelPHP was written.. And since I don't know OOP much, I'm puzzled when this class:
https://github.com/fuel/core/blob/master/classes/date.php
Here are methods that I don't understand:
public static function _init()
{
static::$server_gmt_offset = \Config::get('server_gmt_offset', 0);
// some code here
}
public static function factory($timestamp = null, $timezone = null)
{
$timestamp = is_null($timestamp) ? time() + static::$server_gmt_offset : $timestamp;
$timezone = is_null($timezone) ? \Fuel::$timezone : $timezone;
return new static($timestamp, $timezone);
}
protected function __construct($timestamp, $timezone)
{
$this->timestamp = $timestamp;
$this->set_timezone($timezone);
}
What is called first? What __counctruct does? What is factory, when it's used, what it returns - does it call itself again? Is _init called after initializing class? I'm really puzzled, can someone help me understand? Thanks
When an object is instantiated, the first method to be called is the __construct() method. This is called a constructor because it helps construct the class's data members and do any other initializing operations before you can call other methods int eh class.
A Factory is a creational design pattern used to create classes based on conditions that would not be known until runtime. - http://en.wikipedia.org/wiki/Factory_method_pattern
_init() seems to be another method that this library uses to set up it's classes.
To further your knowledge in these areas, i suggest you read up on OOP and then design patterns.
This class looks like it is using the factory design pattern. Look it up here: PHP - Factory Design Pattern
The factory pattern allows you to instantiate a class at runtime. The _construct method runs as soon as the class is instantiated.

How do you use method injection with Ninject?

I have a class which needs to use an IRepository for one method in it's class.
Ideally, I would like to avoid having to resolve this dependency into the class's constructor, and so I found method level injection in Ninject and was wondering how this works?
I understand how to set it up. What I'm confused about is how to call it?
Example:
class SomeClassThatUsesRepository
{
[Inject]
public void QueryForSomeStuff(IRepository repository)
{
//do some stuff
}
}
My problem is how do I call this method without specifying an IRepository?
var someClass = Kernel.Resolve<SomeClassThatUsesRepository>();
would work if I was using the constructor, but I want to call a method.
How do I call a method using Ninject method injection?
I'm afraid method injection doesn't work this way - it's just one of the ways to inject dependencies into an object during its construction (you can inject your dependencies through constructor parameters, through properties, fields or methods). Method injection is useful if your class takes its dependencies by Java-style setter methods like
public void SetRepository(IRepository repository) { ... }
If it is marked with [Inject] attribute, you don't need to call this methods directly, it is to be called by Ninject during the initialization to pass the IRepository object into your resolved object.
So I believe your QueryForSomeStuff method is being called when you resove your SomeClassThatUsesRepository.
Confirmed that method injection doesn't work as intended. Got a custom MVC attribute class and wanted to use an injected object inside it. Did not pass it
into the constructor and added method
[Ninject.Inject]
public void ResolveDI(ISettingStore store)
{
ConfigHelper = store;
}
This method was never called and ConfigHelper was null when the attribute's OnActionExecuting was called.