PatrickLouys / no-framework-tutorial

A small tutorial to show how to create a PHP application without a framework.
MIT License
1.53k stars 188 forks source link

Part 11 Object to string issue (menu) #62

Closed imilisav closed 7 years ago

imilisav commented 7 years ago

Hi there,

On part 11 after creating the FrontendRenderer and the FrontendTwigRenderer, I ran the server and the error message of "Object of class Example\Template\FrontendTwigRenderer could not be converted to string" is showing. I also changed the references from Renderer to FrontendRenderer in the controllers and removed menu items from the Homepage controller. Do you know what may be happening? If you need any screenshots from my code, please let me know

Thank you for your help.

basherr commented 7 years ago

Paste your controller and FrontendTwigRenderer code

imilisav commented 7 years ago

Homepage controller `<?php declare(strict_types = 1);

namespace Example\Controllers;

use Http\Request; use Http\Response; use Example\Template\FrontendRenderer;

class Homepage { private $request; private $response; private $renderer;

public function __construct(Request $request, Response $response, FrontendRenderer $renderer)
{
    $this->request = $request;
    $this->response = $response;
    $this->$renderer = $renderer;
}

public function show()
{
    $data = [
      'name' => $this->request->getParameter('name', 'stranger'),
    ];
    $this->response->setContent($this->renderer->render('Homepage', $data));
}

} `

FrontendTwigRenderer `<?php declare(strict_types = 1);

namespace Example\Template;

use Example\Menu\MenuReader;

class FrontendTwigRenderer implements FrontendRenderer { private $renderer; private $menuReader;

public function __construct(Renderer $renderer, MenuReader $menuReader)
{
    $this->renderer = $renderer;
    $this->menuReader = $menuReader;
}

public function render($template, $data = []) : string
{
    $data = array_merge($data, [
        'menuItems' => $this->menuReader->readMenu(),
    ]);
    return $this->renderer->render($template, $data);
}

} `

Please let me know if you need anything else.

guyinpv commented 7 years ago

You have a type in the code.

public function __construct(Request $request, Response $response, FrontendRenderer $renderer)
{
    $this->request = $request;
    $this->response = $response;
    $this->$renderer = $renderer; // TYPO HERE, DON'T USE THE DOLLAR SIGN $this->renderer
}

I'm not sure if that's the issue or just a copy error or something but that's what I noticed.

imilisav commented 7 years ago

Oh wow.....that was the issue all along :/ Thanks @guyinpv !