CodeIgniter Forums
Using Event file - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Using Event file (/showthread.php?tid=75777)



Using Event file - EtZeta - 03-16-2020

I don't understand how to use an Event with a separated file with the function Sad

for example

App/Config/Events.php


Quote:Events::on('pre_system', ['compress', 'compresstest']);

System/Events/compress.php


Quote:<?php
function compresstest()
{
console.log("Test");
}


I always have this error: ErrorException call_user_func() expects parameter 1 to be a valid callback, class 'compress' not found

Confused Huh


RE: Using Event file - MGatner - 03-23-2020

You need to pass a valid callback: https://www.php.net/manual/en/language.types.callable.php
If you're going to use the array format it needs to be [$object, $method] where object is an instance or a class name. For example if you have "app/Libraries/Compress.php" you could use something like:
Events::on('pre_system', ['App\Libraries\Compress', 'compresstest']);


RE: Using Event file - EtZeta - 03-23-2020

(03-23-2020, 09:06 AM)MGatner Wrote: You need to pass a valid callback: https://www.php.net/manual/en/language.types.callable.php
If you're going to use the array format it needs to be [$object, $method] where object is an instance or a class name. For example if you have "app/Libraries/Compress.php" you could use something like:
Events::on('pre_system', ['App\Libraries\Compress', 'compresstest']);


Thanks! I solved the problem using this

Events.php

PHP Code:
<?php namespace Config;

use 
CodeIgniter\Events\Events;
use 
App\Eventos\Compress;

$Compress = new Compress();

Events::on('pre_system', [$Compress'Compression']); 

Compress.php

PHP Code:
<?php namespace App\Eventos;

class 
Compress {
public function 
Compression(){

echo 
"test";

  }



Anyway, thank you very much!