简体   繁体   English

实例化PHP类的更好方法

[英]A better way to instantiate a PHP class

I have a class with only one function: 我有一类只有一个功能:

<?php

class EventLog
{

    public function logEvent($data, $object, $operation, $id)
    {
        //Log it to a file...
        $currentTime = new DateTime();
        $time = $currentTime->format('Y-m-d H:i:s');

        $logFile = "/.../event_log.txt";
        $message = "Hello world";

        //Send the data to a file...
        file_put_contents($logFile, $message, FILE_APPEND);
    }

}

Then I have another class with many functions and each and everyone need to call the above method. 然后,我有了另一个具有许多功能的类,每个人都需要调用上述方法。 To instantiate the class in every function I have done: 要在我完成的每个函数中实例化该类:

$log = new EventLog();
//Then...
$log->logEvent($data, $object, $operation, $id);

The problem: I have used the above code in every function and what I would like to know is if there is a way to instantiate the EventLog class once for all the functions that need it. 问题:我在每个函数中都使用了上面的代码,我想知道的是,是否有一种方法可以将所有需要它的函数实例化一次EventLog类。

You can create single instance at the beginning(for example) of your script and inject it into constructors of those classes that need it. 您可以在脚本的开头(例如)创建单个实例,并将其注入需要这些实例的类的构造函数中。 This is called Dependency Injection. 这称为依赖注入。 Most PHP web frameworks utilize this principle. 大多数PHP Web框架都使用此原理。

class Logger
{
   public function writeToLogFile(){
   ...
   }
}


class DoSomethingUseful
{
     private $logger;
     public function __construct(Logger $logger) //php 7 optional type hinting
     {
          $this->logger = $logger;
     }

     public function actualWork()
     {
          //do work
          $this->logger->writeToLogFile('whatever');
     }
}

class Application
{
     public function setUp()
     {
         //create database connection, other stuff
         $this->logger = new Logger;
     }

     public function work()
     {
         $action = new DoSomethingUseful($this->logger);
         $action->actualWork();

     }
}

You could also try using PHP Trait (with namespacing): 您也可以尝试使用PHP Trait(具有命名空间):

<?php
namespace App\Traits;

trait EventLog
{

    public function logEvent($data, $object, $operation, $id)
    {
        //Log it to a file...
        $currentTime = new DateTime();
        $time = $currentTime->format('Y-m-d H:i:s');

        $logFile = "/.../event_log.txt";
        $message = "Hello world";

        //Send the data to a file...
        file_put_contents($logFile, $message, FILE_APPEND);
    }

}

In your other class: 在另一堂课中:

<?php
namespace App;

// import your trait here
use App\Traits\EventLog;

class OtherClass
{
    use EventLog;

    public function sample() {
        // sample call to log event
        $this->logEvent($data, $object, $operation, $id);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM