自定义插件的自动加载不起作用

I have a problem with the autoloading of a custom plugin

I have a plugin blog that's activated in the /config/bootstrap.php

Plugin::loadAll( 'Blog' => ['routes' => true, 'autoload' => true, ]);

In this plugin, I have a table class Article

\plugins\Blog\src\Model\Table\ArticlesTable.php

<?php
namespace Blog\Model\Table;

use \Cake\ORM\Table;
use \Cake\Validation\Validator;

class ArticlesTable extends Table
{
  public function initialize(array $config)
  {
    die('IN ArticlesTable::initialize'); //<-- for the test
    $this->table('articles');
    $this->primaryKey('id');
    $this->addBehavior('Timestamp');
  }

  public function validationDefault(Validator $validator)
  {
  ...
  }
}

In the controller, I manually load the Table

class BlogController extends AppController
{
  public function initialize()
  {
    parent::initialize();
    $this->loadModel('Blog.Articles'); //<----- HERE
  }
...
}

my die('IN ArticlesTable::initialize'); is called.

As in the /config/bootstrap.php, I set to TRUE the 'autoload' parameter, I remove the line

*$this->loadModel('Blog.Articles'); //<----- HERE* in my controller

And here is the problem *die('IN ArticlesTable::initialize');* is not called...

in my /composer.json

"autoload": {
    "psr-4": {
        "App\\": "src",
        "Blog\\": "./plugins/Blog/src",
        "Blog\\Test\\": "./plugins/Blog/tests"
    }
},

Thanks for you help,

Phil

That is the expected behavior, a controllers default model is derived from the controllers name, so for a controller named ArticlesController, it would use Articles and finally ArticlesTable, and in your case with BlogController it's Blog and BlogTable, which doesn't exist.

So either just load the table as you are already doing (in case you need it everywhere in your controller), or make it lazy loading by defining the default class to use via _setModelClass() (in that case the model will be loaded once you access it via $this->Articles).

public function __construct(Request $request = null, Response $response = null, $name = null, $eventManager = null, $components = null)
{
    $this->_setModelClass('Blog.Articles');
    parent::__construct($request, $response, $name, $eventManager, $components);
}

This needs to be done before the parent constructor is invoked, as _setModelClass() only sets the value once!

Thanks ndm for the explain, I understand !

I call _setModelClass in the construct of controller because in the initialize, it doesn't work

class BlogController extends AppController
{

  public function __construct(Request $request = null, Response $response = null, $name = null, $eventManager = null)
  {
    $this->_setModelClass('Blog.Articles');
    parent::__construct($request, $response, $name, $eventManager);
  }
...
}