Welcome Guest, Not a member yet? Register   Sign In
Class not found error with events
#1

I'm migrating a CI3 app to CI4, so naturally that means converting the hooks to events.

I have the following in app/Config/Events.php:

PHP Code:
Events::on('post_controller_constructor', ['Load_config''load_config']); 

In app/Events/Load_config.php I have:

PHP Code:
<?php

namespace App\Events;

use 
app\Libraries\MY_Migration;
use 
app\Models\Appconfig;
use 
CodeIgniter\Session\Session;
use 
Config\Services;

/**
 * @property my_migration migration;
 * @property session session;
 * @property appconfig appconfig;
 * @property mixed $migration_config
 * @property mixed $config
 */
class Load_config
{
    
/**
     * Loads configuration from database into App CI config and then applies those settings
     */
    
public function load_config()
    {
.
.


But when I load the application I'm greeted with "Error Class 'Load_config' not found". I'm assuming that this means that the event loader is not looking where I'm expecting it to look. A couple of questions come up:
- Where should classes formerly in the hooks folder be kept?
- Am I missing a reference in my event call that would cause the event loader to look in app/Events/ to find the class? I thought namespacing the class would take care of that, but perhaps I'm mistaken.
Reply
#2

The classname is not Load_config but \App\Events\Load_config.
Reply
#3

(11-18-2022, 05:09 AM)kenjis Wrote: The classname is not Load_config but \App\Events\Load_config.

Hmmm. That seems counter-intuitive to me. What's the point of namespacing if I then have to put the namespace of the class into the event call?

Nonetheless, I did that and it resolved that problem.
Reply
#4

It is PHP's specification.

When you use namespacing, the classname is  \App\Events\Load_config.
When you specify the classname in a string, you can also write App\Events\Load_config.
If you write Load_config in a string, it means \Load_config and it is the different namespace.

If you use an IDE like PhpStorm and ::class constant, you can write it as \App\Events\Load_config::class,
and IDE can auto complete the classname.

Code:
Events::on('post_controller_constructor', [\App\Events\Load_config::class, 'load_config']); 
Reply




Theme © iAndrew 2016 - Forum software by © MyBB