1

I'm sure this is a trivial mistake but I can't figure it out (first-time plugin dev).

I have my plugin running with all code in the controller and want now follow best practice and move the workhorse code into a service class.

My main plugin code is

namespace ns\yutulic;
use ns\yutulic\models\SettingsModel;
use craft\models\Section;

public function init() {

    parent::init();

    self::$plugin = $this;

    $settings = $this->getSettings();
    $settings->sectionOptions = $this->setSectionOptions();

    // Register services
    $this->setComponents([
        'videoentries' => \ns\yutulic\services\VideoEntriesService::class,
    ]);

    $data = $this->videoentries->scanForVideos(null); // works

}

The relevant controller code is

Class ScanController extends Controller {
    public function actionScanEntries() {
        // Neiter works :-(
        //$data = Yutulic::$plugin->videoentries->scanForVideos($id);
        $data = Yutulic::getInstance()->videoentries->scanForVideos($id); // (*)
    }
}

And my service code:

<?php
namespace ns\yutulic\services;
use ns\yutulic\Yutulic;
use Craft;
use craft\base\Component;

class VideoEntriesService extends Component
{
    public function scanForVideos($sectionId = null) {
        echo "Works!!!";
        return null;
    }
}

Even if I use the example of the docs it fails with the same error message on the line indicated (*) in the controller (but with the 'Foo' class name):

Class 'ns\yutulic\Yutulic' not found

This shouldn't be so hard?

  • What's the name and class of your main plugin file? – RoussKS Feb 19 at 9:08
  • 1
    @RoussKS That was indeed the problem (see my answer below). I had copied code from an example that was different from all other plugins I reviewed. Eventually it dawned on me that the class name was wrong. – Crafty Cat Feb 20 at 22:05
  • It was an instant thought (even though simplistic. Happens to the best of us :) glad you sorted it out. – RoussKS Feb 21 at 7:39
1

I found the issue. The author of the tutorial I copied my first code from made the unfortunate choice to not use a proper plugin class:

class Plugin extends \craft\base\Plugin { ... }

To fix the problem, I replaced this line with

use Craft;
use craft\base\Plugin;
class Yutulic extends Plugin { ... }

and had to add a reference to the class to my controller and service modules:

use ns\yutulic\Yutulic;
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.