简体   繁体   中英

File handling functions in PHP class

I am trying to debug some scripts that I've done that don't work. I want to implement the very basic logging (I mean log files) function that I use in the main page script in my class files.

However it doesn't work, for example these simple lines:

if ($file = fopen('C:/wamp/www/xxxx/Logs/General/' . date('Ymd') . '.log', 'a+') {

    fputs($file, "[" . date('d/m/Y - H:i:s') . "]\t" . "[" . $type ."]\t" . "[" . $author . "]\t" . $message . "\r\n"); 
    fclose($file);
}
else 
{
    return false;
}

Work perfectly if I put them in a php function included at the top of my main page (for example in a log.php file). Howevr they don't work at all if they are in a class method:

public function __contruct(array $connectionArgs)
{
    if ($file = fopen('C:/wamp/www/xxxx/Logs/General/' . date('Ymd') . '.log', 'a')) {
        fwrite($file, "test");
        fclose($file);
    }
    else
    {
        die("fail");
    }

I am quite new to OOP so I guess it has something to do with the way of calling such function into a class?

It shoudln't be a different if you're putting your logger in class definition or in function code. I assume that you're doing something wrong or maybe you have some error.

Here this is working example

Class Logger
{
    const PATH_TO_LOGS_DIRECTORY = 'C:/wamp/www/xxxx/Logs/General/';
    const FILE_DATE_SUFFIX = 'Ymd';
    private $handle;

    public function log($what) {
        $this->openFile();
        fwrite($this->handle, $what . PHP_EOL);
    }

    protected function openFile() {
       if ($this->handle === null) {
          $this->handle = fopen(self::PATH_TO_LOGS_DIRECTORY . date(self::FILE_DATE_SUFFIX) . '.log', 'a');
          if ($this->handle === false) {
             throw new RuntimeException('Cannot open log file');
         }
       }
       register_shutdown_function(array($this, 'close'));
    }



    public function close() {
        if($this->handle !== null) {
            fclose($this->handle);
        }
    }

}

Few extra things that you should care of :

  1. don't open file till you want to log something. When you're not logging stuff you don't need to reach the file and seek to end of file.. It's called Lazy Initialiation. When you want to log something they you're opening file
  2. in this demo class I'm using a small trick, normally when you're shuttingdown application you should close the log file, (call fclose()), but then you have remember that, and then if you have exception you have to handle that also. But you can use register_shutdown_function and PHP will always call that function on the end of php script
  3. take a look on PSR-3 ( https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md ) - PHP group is trying to standarize the logging systems so there is no need to to write your own interface to handle
  4. it's good to pass date string (timestamp or DateTime object event better a param to constructor. You should pass dependency, not expect them

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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