2myCharlie
2myCharlie

Reputation: 1947

How do I resolve a "Fatal error" when creating a service?

I'm following this Drupal 8 module development 101 tutorial. It's between 37:15 to 45:14 on the YouTube video. I kept getting this error:

Fatal error: Class 'Drupal\dino_roar\DinoServices\HelloGenerator' not found in C:\Users\myName\Sites\devdesktop\drupal-8.0.5\modules\dino_roar\src\Controller\RoarController.php on line 11

Folder structure: enter image description here

HelloGenerator.php

<?php

namespace Drupal\dino_roar\DinoServices;

class HelloGenerator
{
    public function getHello($count){
        return "Gotten Hello ".$count;
    }
}

RoarController.php

<?php

namespace Drupal\dino_roar\Controller;

//use Drupal\dino_roar\DinoServices\HelloGenerator;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class RoarController extends Controller
{
    public function roar($count){
        //$helloGenerator = new HelloGenerator();
        $helloGenerator = $this->get('dino_roar.hello_generator');
        $hello = $helloGenerator->getHello($count);
        return new Response($hello);

        //return new Response("Hello World ".$count);
    }
}

dino_roar.info.yml

name: Dino ROAR
type: module
description: "ROAR at you"
package: Custom
core: 8.x

dino_roar.routing.yml

dino_says:
    path: /dino/says/{count}
    defaults:
        _controller: '\Drupal\dino_roar\Controller\RoarController::roar'
    requirements:
        _permission: 'access content'

dino_roar.services.yml

services:
    dino_roar.hello_generator:
        class: Drupal\dino_roar\DinoServices\HelloGenerator

The fatal error points to this line of code in the RoarController.php file: $helloGenerator = new HelloGenerator();

This is the Symfony version. I can't find it say 1,2, or 3 in this window.

enter image description here

Upvotes: -1

Views: 200

Answers (1)

Fran&#231;ois Dupont
Fran&#231;ois Dupont

Reputation: 424

First of all, your RoarController class needs to extends the Controller class

class RoarController

to

use Symfony\Bundle\FrameworkBundle\Controller\Controller

class RoarController extends Controller

EDIT

Ok now change

public function roar($count){
    $helloGenerator = new HelloGenerator();
    $hello = $helloGenerator->getHello($count);
    return new Response($hello);

    //return new Response("Hello World ".$count);
}

to

public function roar($count){
    $helloGenerator = $this->get('dino_roar.hello_generator');
    $hello = $helloGenerator->getHello($count);
    return new Response($hello);

    //return new Response("Hello World ".$count);
}

You didn't understand how use services that why I invite you to read this http://symfony.com/doc/current/book/service_container.html#creating-configuring-services-in-the-container

Upvotes: 1

Related Questions