简体   繁体   中英

How can I use HTMLPurifier inside a PHP class?

As the title states; how can I use the HTMLPurifier library inside my class?

I'm trying to get to grips with OOP and PHP classes for the first time and have successfully built a class that connects to my database using my database class and returns a blog article.

I would now like to parse the HTML markup for the blog article using HTMLPurifier but I would like to achieve this inside my blog class and I'm wondering how it can be achieved, as HTMLPurifier is a class.

My class so far:

namespace Blog\Reader;

use PDO;
use HTMLPurifier_Config; <--- trying to include it here
use \Database\Connect;

class BlogReader {
   private static $instance = null;
   private static $article = null;
   private static $config = null;
   private static $db = null;

   private static function InitDB() {
      if (self::$db) return;
      try {
         $connect = Connect::getInstance(self::$config['database']);
         self::$db = $connect->getConnection();
      } catch (Throwable $t) {}
   }

   private function __construct($config) {
      self::$config = $config;
   }

   public static function getInstance($config) {
      if (!self::$instance) {
         self::$instance = new BlogReader($config);
      }
      return self::$instance;
   }

   public static function getArticle($id) {
      self::InitDB();

      try {
         if (self::$db) {
            $q = self::$db->prepare("
               // sql
            ");
            $q->bindValue(':id', (int) $id, PDO::PARAM_INT);
            $q->execute();
            self::$article = $q->fetchAll(PDO::FETCH_ASSOC);


            //////////// <----- and trying to use it here

            $HTMLPurifier_Config = HTMLPurifier_Config::createDefault();
            $purifier = new HTMLPurifier($HTMLPurifier_Config);

            ///////////


         } else {
            throw new Exception("No database connection found.");
            self::$article = null;
         }
      } catch (Throwable $t) {
         self::$article = null;
      }

      return self::$article;
   }

   private function __clone() {}
   private function __sleep() {}
   private function __wakeup() {}
}

However, I get the following error log when trying anything like this:

Uncaught Error: Class 'HTMLPurifier_Config' not found in ....../php/classes/blog/reader/blogreader.class.php

And the line number of the error is on this line:

$HTMLPurifier_Config = HTMLPurifier_Config::createDefault();

My class directory structure:

[root]
    [blog]
        blog.php   <--- using classes here
    [php]
        afs-autoload.php
        [classes]
            [blog]
            [database]
            [vendor]
                [htmlpurifier-4.10.0]
                    [library]
                        HTMLPurifier.auto.php  <--- this is what I used to `include` on blog.php to autoload HTMLPurifier_Config::createDefault() and new HTMLPurifier($purifier_config).

My Autoloader (afs-autoload.php) file:

define('CLASS_ROOT', dirname(__FILE__));

spl_autoload_register(function ($class) {
   $file = CLASS_ROOT . '/classes/' . str_replace('\\', '/', strtolower($class)) . '.class.php';
   if (file_exists($file)) {
      require $file;
   }
});

I literally started learning classes today, so I'm really baffled as to how I can achieve this, especially with the namespace system I used.

I hope somebody with better experience can guide me in the right direction.

Rewritten answer:

1) Your auto loader is looking for <class>.class.php files; but your HTMLPurifier_Config is in a HTMLPurifier.auto.php file.

2) Still in your autoloader: str_replace('\\\\' You do not need to escape characters when in single quotes, so this should be: str_replace('\\' .

3) This excellent answer should help you learn when and how to use the use PHP keyword.

4) Your issue is not the scope of your use (I don't think you even need to use use ). But is that your autoloader is looking for the wrong type of files. Try manually loading the class using require and seeing if it works properly.


Original Answer

namespace Blog\Reader;

use PDO;
use HTMLPurifier_Config;

What you're actually doing here is using the values within the defined namespace ; so you're using:

 Blog\\Reader\\HTMLPurifier_Config

If you're HTMLPurifier_Config file is within its own namespace you need to specify that so that the "use" grabs the right data!

If its not in its own namespace then it will be in the global namespace which is identified with a slash:

namespace Blog\Reader;

use PDO;
use \HTMLPurifier_Config;

If it is in the namespace HTMLPurifier , for example:

namespace Blog\Reader;

use PDO;
use \HTMLPurifier\HTMLPurifier_Config;

to load the correct data reference.

Just to wrap this up, if you are using namespaces inside a class which as been placed in a namespace , this is how you create your purifier objects:

$config = \HTMLPurifier_Config::createDefault();
$purifier = new \HTMLPurifier($config);
$clean_html = $purifier->purify($dirty_html);

You do not have to use a use command since the HTMLPurifier classes themselves are not in a namespace. But when your code is in a namespace , you need to pre-pend '\\' to non-namespaced classes.

namespace \Tdiscus;  // This is the line that makes the difference.
use \Tsugi\Util\Net;

class Threads {
    ...
    $config = \HTMLPurifier_Config::createDefault();
    ...
    $retval = new \stdClass();
    ...
    $dbh = new \PDO($dsn, $user, $password);
}

Because you placed the class in a namespace, any "non-namespaced" classes need a "" prefix - like PDO and stdClass in the above example.

The HTMLPurifier folks could have put their classes in a namespace - but they chose not to do that.

Using namespaces is a common practice when developing libraries intended for use with composer . But HTMLPurifier existed before composer was in common use and their classes have a nice unique prefix because they started out in a global class namespace - so they decided to leave well enough alone and not break the non-dynamic loading / non-namespace legacy adopters of their library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM