سؤال

I'm using Zend Framework 2 to do some work, here I need to cleanup user's input, which is in Html. I've used php tidy extension [see this] before in plain php without the use of namespace and autoloading, and that code goes just fine.

while this time, I wrote a view helper in zf2, which is like:

<?php
namespace Blog\View\Helper;
use Zend\View\Helper\AbstractHelper;

class TidyHtml extends AbstractHelper
{
    public function __invoke($userHtml){
    $config = array(
               'indent'         => true,
               'output-xhtml'   => true,
               'wrap'           => 200);

    $userHtml = '<div id="wrapper">'.$userHtml.'</div>';
    $tidy = new tidy();
    $tidy->parseString($userHtml,$config,'utf8');

    $tidy->cleanRepair();
    $dom = new DOMDocument();
    $dom->loadHTML($tidy);

    $node = $dom->getElementsById("wrapper");
    $newdoc = new DOMDocument();
    $cloned = $node->item(0)->cloneNode(TRUE);
    $newdoc->appendChild($newdoc->importNode($cloned,TRUE));
    return $newdoc->saveHTML();
    }
}

I want to create an instance of tidy in line 14, but an error raised:

PHP Fatal error:  Class 'Blog\\View\\Helper\\tidy' not found in /var/www/zf2-tutorial
/module/Blog/src/Blog/View/Helper/TidyHtml.php on line 14

aparently php treat tidy as some user-defined class and can't find its declaration. maybe the autoloading function in zf2 have some influence on it. and I'm sure tidy2.0 extension is properly installed on my machine.

هل كانت مفيدة؟

المحلول

The problem here is caused by the fact that you are in namespace Blog\View\Helper as declared in your code, and since you call the class tidy without its fully qualified name, PHP supposes you actually want Blog\View\Helper\tidy.

Simply do $tidy = new \tidy(); and you should be fine, notice the prepended slash.

You might also want to read more about namespaces in PHP: http://php.net/manual/en/language.namespaces.php

Also, you might need to do use the fully qualified class name for all the other classes from the root namespace, and in general from namespaces other than the current one, or issue the proper use statement, as explained here: http://php.net/manual/en/language.namespaces.importing.php

نصائح أخرى

You're wise suggested to read about namespaces

You're inside the namespace Blog\View\Helper. This means, that when you create a new tidy(); it is looking for Blog\View\Helper\tidy. If a class is within the global namespace you'd need to call new \tidy(), same with DOMDocument.

if a class is within a different namespace, you need to either use it like:

use Some\Name\Space\Tidy;
new Tidy();

or do it like

new \Some\Name\Space\Tidy();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top