0

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.

tereško
  • 58,060
  • 25
  • 98
  • 150
ao-pack
  • 27
  • 6
  • 2
    Check this one https://stackoverflow.com/questions/1257371/when-do-i-use-static-variables-functions-in-php – mim. Jul 27 '17 at 08:24
  • 1
    Use dependency injection and bind the `EventLog` as a singleton or make the method static. – apokryfos Jul 27 '17 at 08:25
  • Thanks, I had a look but it says 'not really useful in PHP'. – ao-pack Jul 27 '17 at 08:29
  • Could he not simply make a `public $log` and in the constructor of his class he simply d `$log = new EventLog();` - the method `logEvent` should then also be available in every method of the other class, or I am wrong? – Twinfriends Jul 27 '17 at 08:30
  • _"but it says 'not really useful in PHP'."_ - Well, static methods can definitely be useful in PHP. They can also be misused. In your case, I would go for Dependency Injection, though. – M. Eriksson Jul 27 '17 at 08:40

2 Answers2

1

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.

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();

     }
}
svgrafov
  • 1,970
  • 4
  • 16
  • 32
  • Could it be because the class where I need the instantiation extends another class that implements another one? For instance the class where i need to call the EventLog class is defined as folllows: class Party extends Component implements Validatable – ao-pack Jul 27 '17 at 09:02
  • Parse error: syntax error, unexpected '$log' (T_VARIABLE), expecting function (T_FUNCTION) in /home/../... – ao-pack Jul 27 '17 at 09:08
  • This is the way I've instantiated it: class myClass extends Component implements Validate { $log = new EventLog(); public function add(){ $log->logEvent(param1, param2, param3, param4); } } – ao-pack Jul 27 '17 at 09:08
  • I believe your syntax error is because you have this line "$log = new EventLog();" right after class name declaration, instead of inside function. – svgrafov Jul 27 '17 at 09:30
  • That worked. Thanks a lot mate!! I did adapt the code to php 5.6 though. Cheers!! – ao-pack Jul 27 '17 at 10:15
0

You could also try using PHP Trait (with namespacing):

<?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);
    }

}
elegisandi
  • 454
  • 3
  • 10