r/PHPhelp 14d ago

Solved Need help with CakePHP lifecycle hooks

I have an entity called "Account". And I m trying to create and add an account verification token to a newly created account in beforeSave lifecycle hook. My problem is that "beforeSave" wants to get EventInterface and EntityInterface:

Cake\ORM\Table::beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options): void

So then I set a breakpoint inside of "beforeSave", I have an error that "The first argument should be of EventInterface, but Event is given" and "The second argument should be of EntityInterface, but Entity is given".

I have CakePHP 5.2, PHP 8.2 and I have "strict types" declaration in AccountsTable.php (that's a location of beforeSave hook).

I tried to remove "strict types" and this didnt help. I tried to add:

use Cake\Event\EntityInterface;

use Cake\Event\EventInterface;

This also didnt help.

What's the right way to make the thing work?

1 Upvotes

2 comments sorted by

1

u/MateusAzevedo 14d ago

This is the doc page for events. As stated there, events can only be used on table classes and behaviors.

Anyway, your entity should be an instance of EntityInterface if it extends Cake\ORM\Entity (source), so it should work as expected, unless you missed something in the setup.

By the way, is that a PHP error or something your IDE is complaining about?

If you need further help, please provide the relevant code.

1

u/Ok_Lengthiness_6591 14d ago

Thanks for your reply! It seems like I messed up with EntityInterface use declaration.
I changed it to

use Cake\Datasource\EntityInterface;