The __destruct() is an interesting magic method which triggers at the very end of all the object's references.
First Example
class DatabaseWrapper
{
public function __construct(){
var_dump('connection open');
}
public function query($query){
var_dump('run ' . $query);
}
public function __destruct(){
var_dump('connection closed');
}
}
$wrapper = new DatabaseWrapper();
$wrapper->query('select * from users');
This is a very basic example to understand how __destruct()
magic method works. In this example, we’ve a simple scenario where a database connection opens, we runs a query and later close the connection. If we run this script, we’ll get the following output.
string(15) "connection open"
string(23) "run select * from users"
string(17) "connection closed"
Hence as we’ve seen __destruct()
magic method triggers at the very end of all the references withing the class.
Another Example (Job Dispatcher)
Again this example inspired from Laravel, and we’ll create a simple job dispatcher class and look at how __destruct()
magic method works here.
We’ll be creating a simple email dispatcher and we’d want to implement a delay of 5 minutes before each dispatch. Here we’ve used a Dispatchable
trait, if you’re not familiar with what a trait does, you can check out Traits in PHP.
class Job
{
public $delay = 0;
public function delay($delay){
$this->delay = $delay;
}
}
trait Dispatchable
{
public function dispatch(){
return new PendingDispatch(new static);
}
}
class PendingDispatch
{
protected $job;
public function __construct(Job $job){
$this->job = $job;
}
public function delay($delay){
$this->job->delay($delay);
return $this;
}
public function __destruct(){
var_dump('dispatched job ' . get_class($this->job) . ' with a delay of '. $this->job->delay);
}
}
class EmailUser extends Job
{
use Dispatchable;
public function handle(){
var_dump("send email to user");
}
}
$job = new EmailUser();
$job->dispatch()->delay(5);
As you can see, we’ve used the __destruct()
magic method in PendingDispatch
class as delay()
is the last of references or operations to run and we can put our __destruct()
magic method there.