PHP在删除自动加载器后,Composer会使工作失败

时间:2018-08-04 20:18:50

标签: php namespaces composer-php autoloader psr-4

我正在关注Lopez的“ Learning PHP 7”(学习PHP 7)书,并在Ch。在MVC上获得5分,我将不胜感激,以了解这里的问题所在。

在init.php中,我注释掉了-请参阅init.php中的9行注释-自动加载器函数,Lopez写道,不再需要了,该错误:

  

PHP致命错误:未捕获的错误:在/home/petr/Documents/workspace/bookstore/init.php:25中找不到类'Bookstore \ Utils \ Config'   堆栈跟踪:   ...

init.php中的第25行(完整显示如下)

$dbConfig = Config::getInstance()->get('db');

((在安装PHP,MySQL,Composer和Twig时,我没有使用Vagrant [在开始本书之前已在Ubuntu上安装了PHP,MySQL和Apache,并且今天通过Synaptic添加了Composer w。Twig)。开发此项目的默认Web服务器。)

项目结构如下:

enter image description here

init.php就像这样:

<?php

use Bookstore\Domain\Customer\Basic;
use Bookstore\Domain\Customer\Premium;
use Bookstore\Domain\Customer\CustomerFactory;
use Bookstore\Domain\Customer;
use Bookstore\Domain\Payer;
use Bookstore\Domain\Person;
use Bookstore\Domain\Book;
use Bookstore\Utils\Config;
use Bookstore\Utils\Unique;
use Bookstore\Exceptions\InvalidIdException;
use Bookstore\Exceptions\ExceededMaxAllowedException;

// function autoloader($classname) {
//   $lastSlash = strpos($classname, '\\') + 1;
//   $classname = substr($classname, $lastSlash);
//   $directory = str_replace('\\', '/', $classname);
//   $filename = __DIR__ . '/' . $directory . '.php';
//   require_once($filename);
// }
//
// spl_autoload_register('autoloader');

$dbConfig = Config::getInstance()->get('db');
$db = new PDO(
  'mysql:host=127.0.0.1;dbname=bookstore',
  $dbConfig['user'],
  $dbConfig['password']

);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

function addBook(int $id, int $amount = 1): void {
  $db = new PDO(
    'mysql:host=127.0.0.1;dbname=bookstore',
    'root',
    ''
  );

  $query = 'UPDATE book SET stock = stock + :n WHERE id = :id';
  $statement = $db->prepare($query);
  $statement->bindValue('id', $id);
  $statement->bindValue('n', $amount);

  if (!$statement->execute()) {
    throw new Exception($statement->errorInfo()[2]);
  }
}

function addSale(int $userId, array $bookIds): void {
  $db = new PDO(
    'mysql:host=127.0.0.1;dbname=bookstore',
    'root',
    ''
  );

  $db->beginTransaction();
  try {
    $query = 'INSERT INTO sale (customer_id, date) '
        . 'VALUES(:id, NOW())';
    $statement = $db->prepare($query);
    if (!$statement->execute(['id' => $userId])) {
      throw new Exception($statement->errorInfo()[2]);
    }
    $saleId = $db->lastInsertId();

    $query = 'INSERT INTO sale_book (book_id, sale_id) '
        . 'VALUES (:book, :sale)';
    $statement = $db->prepare($query);
    $statement->bindValue('sale', $saleId);
    foreach ($bookIds as $bookId) {
      $statement->bindValue('book', $bookId);
      if (!$statement->execute()) {
        throw new Exception($statement->errorInfo()[2]);
      }
    }

    $db->commit();
  }
  catch (Exception $e) {
    $db->rollBack();
    throw $e;
  }
}

try {
  addSale(1, [3, 7]);
}
catch (Exception $e) {
  echo 'Error adding sale: ' . $e->getMessage();
}

composer.json是此文件:

{
  "require": {
    "monolog/monolog": "^1.17",
    "twig/twig": "^1.23"
    },
  "autoload": {
    "psr-4": {
      "Bookstore\\": "bookstore"
      }
    }
}

这是Config.php:

<?php

namespace Bookstore\Utils;

use Bookstore\Exceptions\NotFoundException;

class Config {

  private static $data;     // private $data;
  private static $instance;

  private function __construct() {     // public function __construct() {

    $json = file_get_contents(__DIR__ . '/../config/app.json');
    self::$data = json_decode($json, true);     // $this->data = json_decode($json, true);

  }

  public static function getInstance() {
    if (self::$instance == null) {
      self::$instance = new Config();
    }

    return self::$instance;

  }

  public static function get($key) {      // public function get($key) {

     if (!isset(self::$data[$key])) {     // if (!isset($this->data[$key])) {
     throw new NotFoundException("Key $key not in config.");

  }
  return self::$data[$key];     // return $this->data[$key];

  }

}

我想知道如何使项目与从init.php中删除的功能autoloader一起工作。谢谢。

1 个答案:

答案 0 :(得分:1)

您需要一个自动加载器来神奇地加载类。当您使用依赖项和PSR-4自动加载规则定义了composer.json时,我建议使用Composers自动加载器。

您的composer.json配置有一个小错误:PSR-4自动加载器尝试从名为Bookstore的子文件夹中加载bookstore名称空间中的类。这些类位于项目的根目录中。因此,自动加载器必须指向该目录,而不必将目录路径留空:

{
  "require": {
    "monolog/monolog": "^1.17",
    "twig/twig": "^1.23"
    },
  "autoload": {
    "psr-4": {
      "Bookstore\\": ""
      }
    }
}