开发者

Adding custom classes / methods

I have created a task in Symfony 1.4 that loads in some CSV files into a table - very simple ->

protected function execute($arguments = array(), $options = array())
{
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = $databaseManager->getDatabase($options['connection'])->getConnection();

    ......

    $query = "LOAD DATA INFILE '" . $cdrfile . "'
       INTO TABLE .... 

    etc

    $connection->execute($query);
}

But i want to reuse this section of code else where - So i create a n开发者_JAVA百科ew PHP Class and created a new static method called loadDataFromCSV.

I put all of the code into that method and then called class::loadDataFromCSV ...

This gave me some problems - first the $this keyword in the method is not valid as the class it not an object (ie not instantiated) - so I could instantiate the class and then call the method class->loadDataFromCSV - the next problem is the $this->configuration on the first line - do I have to pass in the configuration to the method to get it working ?

Whats the simplest way to create a simple method to run a simple piece of code - without having to pass lots of variables around.


Short answer: Use DI Container.

Long answer: You basically ask how to set object dependencies as your class depends on configuration object. There are two ways to do this. Hardcode dependency in your class. e.g. Registry::getInstance()->get('config'); and to use dependency injection. Dependency injection is better solution as far as you can pass any config instance. Existing Object, new object, mock object for unit testing, or other config implementation. There are two types of dependency injection. inject dependency via constructor (e.g. new Object(new Dependency())) or via setter.

$o = new Object();
$o->setDependency($dependency);

If your object has many dependencies the code may become little unreadable in both ways. The solution is to use Dependency Injection Container which inject automatically all the dependencies for you. Your client code is still one simple line: DIContainer::create('object');. Create method creates an instance of class, inject all the dependencies and returns the object.


For using your approach with static method you should:

  1. Replace all this-> keywords on self::
  2. Move all config settings in one file and load them in for example Config class which will implement pattern Singleton.
  3. Call will look like Config::getInstance()->getSection('your_section');

Regarding DB initialization:

  1. Create Registry class with 2 static methods set/get
  2. Create a DB object in bootstrap file.
  3. Use $connection = Registry::get('db')->getConnection();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜