mercredi 7 février 2018

PHP Custom Exceptions Design Pattern

So I have let's say a few custom Exceptions now but i think I will have a lot more let's say over 10+. I am trying to find a design pattern or way of not writing the same code on each Exception.

Here is what I have in one file

<?php
/**
* Define a custom exception class
*/

class MyException extends Exception
{
    // Redefine the exception so message isn't optional
    public function __construct($message, $code = 0) {
    // some code

    // make sure everything is assigned properly
        parent::__construct($message, $code);
    }

}

class MyException2 extends Exception
{
    // Redefine the exception so message isn't optional
    public function __construct($message, $code = 0) {
    // some code

    // make sure everything is assigned properly
        parent::__construct($message, $code);
    }

}

class MyException3 extends Exception
{
    // Redefine the exception so message isn't optional
    public function __construct($message, $code = 0) {
    // some code

    // make sure everything is assigned properly
        parent::__construct($message, $code);
    }

}

// below there will be many other Exceptions that will have different names

So where is says //code I will be adding a logger for example. So i would like to just pass a parameter or something so I don't have to repeat that whole construct on each and then the log stuff being almost the same.

Not sure if there is some design pattern around for this. If there is please let me know.

Aucun commentaire:

Enregistrer un commentaire