简体   繁体   English

如何在 PHP 类中使用 HTMLPurifier?

[英]How can I use HTMLPurifier inside a PHP class?

As the title states;正如标题所说; how can I use the HTMLPurifier library inside my class?如何在我的班级中使用HTMLPurifier库?

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.我正在尝试第一次掌握 OOP 和 PHP 类,并成功构建了一个类,该类使用我的数据库类连接到我的数据库并返回一篇博客文章。

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.我现在想使用 HTMLPurifier 解析博客文章的 HTML 标记,但我想在我的博客类中实现这一点,我想知道如何实现,因为 HTMLPurifier 是一个类。

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未捕获的错误:在....../php/classes/blog/reader/blogreader.class.php 中找不到类“HTMLPurifier_Config”

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:我的自动加载器 (afs-autoload.php) 文件:

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; 1) 你的自动加载器正在寻找<class>.class.php文件; but your HTMLPurifier_Config is in a HTMLPurifier.auto.php file.但您的HTMLPurifier_Config位于HTMLPurifier.auto.php文件中。

2) Still in your autoloader: str_replace('\\\\' You do not need to escape characters when in single quotes, so this should be: str_replace('\\' . 2)仍然在你的自动加载器中: str_replace('\\\\'你不需要在单引号中转义字符,所以这应该是: str_replace('\\'

3) This excellent answer should help you learn when and how to use the use PHP keyword. 3)这个优秀的答案应该可以帮助您了解何时以及如何使用use PHP 关键字。

4) Your issue is not the scope of your use (I don't think you even need to use use ). 4)您的问题不在于您的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.尝试使用require手动加载类并查看它是否正常工作。


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!如果你的HTMLPurifier_Config文件在它自己的命名空间内,你需要指定它,以便“使用”获取正确的数据!

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:如果它在命名空间HTMLPurifier ,例如:

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:总结一下,如果您在放置在namespace的类中使用命名namespace ,这就是您创建净化器对象的方式:

$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.不必使用use自HTMLPurifier类本身不是一个命名空间命令。 But when your code is in a namespace , you need to pre-pend '\\' to non-namespaced classes.但是,当您的代码位于namespace ,您需要在非命名空间类之前添加 '\\'。

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.因为您将类放置在命名空间中,所以任何“非命名空间”类都需要一个 "" 前缀 - 如上例中的PDOstdClass

The HTMLPurifier folks could have put their classes in a namespace - but they chose not to do that. HTMLPurifier 人员本可以将他们的类放在命名空间中 - 但他们选择不这样做。

Using namespaces is a common practice when developing libraries intended for use with composer .在开发旨在与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.但是 HTMLPurifier 在 Composer 被普遍使用之前就已经存在,并且它们的类有一个很好的唯一前缀,因为它们是在全局类命名空间中开始的——所以他们决定保持足够的独立性,而不是打破非动态加载/非命名空间的传统采用者他们的图书馆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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