inflearn logo
강의

Course

Instructor

PHP 7+ Programming: Object-Oriented

class not found

328

choisw73564306

7 asked

1

안녕하세요, 선생님!

나만의 프레임워크 강의 내용을 카피코딩하면서 class not found 에러가 발생하여 질문남깁니다.

 

-에러내용

Fatal error: Uncaught Error: Class "Eclair\Database\Adaptor" not found in C:\xampp\ECLAIR\index.php:11 Stack trace: #0 {main} thrown in C:\xampp\ECLAIR\index.php on line 11

 

-index.php

<?php

require './vendor/autoload.php';


use Eclair\Routing\Route;
use Eclair\Database\Adaptor;

Adaptor::setup('mysql:dbname=myapp_test','root', '');

Route::add('get','/', function(){
    echo 'Hello, world';
})
/*
Route::add('get','/posts/{$id}', function (){
    var_dump(Adaptor::getAll('SEELCT * FROM posts WEHRE `id` = ?', [$id]))
})

Route::run();
*/
?>

 

-Route.php

<?php

namespace Eclair\Routing;

use Eclair\Routing\RequestContext;

class Route
{
    private static $contexts = [];

    public static function add($method, $path, $handler, $middlewares = [])
    {
        self::$contexts[] =  new RequestContext($method, $path, $handler, $middlwares);

    }

    public static function run()
    {
        foreach($contexts as $context){
            if($context -> method === strtolower(Request::getMethod()) && is_array($urlParams = $context->match(Request::getPath()))){
                if($context -> runMiddlewares()){
                    return call_user_func($context->handler, ...$urlParams);

                }
                return false;
            }
        }
    }

}

 

-RequestContext.php

<?php

namespace Eclair\Routing;

class RequestContext
{
    public $method;
    public $path;
    public $handler;
    public $middlewares;

    public function __construct($method, $path, $handler, $middlewares)
    {
        $this->method = $method;
        $this->path = $path;
        $this->handler = $handler;
        $this->middlewares = $middlewares;
    }

    public function match($url)
    {
        //$this->path => /posts/{$id}, $url => /posts/1
        $urlParts = explode('/',$url);
        $urlPatternParts = explode('/',$this->path);

        if(count($urlParts) === count($urlPatternParts)){
            $urlParams = [];

            foreach($urlPatternParts as $key => $part){
                if(preg_match('/^\{.*\}$/', $part)){
                    $urlParams[$key] = $part;
                } else{
                    if($urlParts[$key]!= $part){
                        return null;
                    }
                }
            }
        }
            return count($urlParams) < 1
            ? [] 
            : array_map(fn($k) => $urlParts[$k], array_keys($urlParams));
    }

    public function runMiddlewares()
    {
        foreach($this->middlewares as $middlewares){
            if(! $middlewares::process()){
                return false;
            }
        }
        return true;
    }
}

 

-adaptor.php

<?php

namespace Eclair\Database;

class Adaptor
{
    public static $pdo;

    private static $sth;

    public static function setup($dsn, $username, $password)
    {
        self::$pdo = new \PDO($dsn, $username, $password);
    }

    public static function exec($query, $params)
    {
        if(self::$sth = self::$pdo -> prepare($query)){
            return self::$sth -> execute($params);
        }
    }

    public static function getAll($query, $params = [], $classname = 'stdClass')
    {
        if(self::exec($query, $params)){
            return self::sth -> fetchAll(\PDO::FETCH_CLASS, $classname);
        }
    }

    public static $test = 'test';

    public static function output()
    {
        return self::$test;
    }

}

 

현재, 모든 Route클래스를 포함한 모든 클래스들이 호출되지 않는 것 같습니다.

코드와 디렉토리 구조 모두 강의 내용과 일치한데, 어디에서 문제가 발생한 것인지 감도 안 잡히네요..ㅜㅜ

autoload.php파일을 건드린 적이 없는데, 이 파일이 문제인 걸까요??

 

oop php

Answer 1

1

pronist

안녕하세요.

composer.json 에 psr-4 매핑이 올바르게 되어있다면 에러가 날 일이 없기는 한데, composer dump-autoload 라는 명령어를 입력해보시겠어요? 저번 질문에서 composer.json 을 변경하신 듯 해서 확실하지는 않지만 가능성이 있는 해결법을 말씀드립니다.

0

choisw73564306

안녕하세요, 선생님! 선생님 말씀대로 따라 하니 해결되었어요!

감사합니다 :)

패케지스트를 하지 않고 섹션7을 수행할수 있나요

0

90

1

나만의 프레임워크 작성 후, 운영환경 배포에 관한 문의 드려요

0

402

1

35강 미들웨어에서 인증 과정을 Auth클래스로 만들면, 어느 디렉토리에 둘까요?

0

335

1

ios환경에서는 어떻게 설치해야 하나요?

0

448

1

라라벨(php) 배포 문의

0

1652

1

왜 http://localhost/ 로 접근하면 public/index.php 가 실행되나요?

0

2102

1

http://localhost:8080/posts/1 접근시 배열 0값 표기 오류

0

397

1

xdebug 설치

0

668

1

localhost 경로

0

441

1

namespace class not found 질문

0

466

1

csrfmiddelware 에러 질문입니다

0

363

2

url Parttern Parts 가 무슨뜻인가요?

0

349

1

통합 개발환경 (IDE) 관련 문의

0

248

1

Route 클래스 질문이 있습니다!

0

297

1

모델 User 등에서 속성들을 protected 나 private 으로 설정하지 않는 이유가 있습니까?

0

340

1

안녕하세요 프로젝트를 react와 연동하기에 대해서 여쭈고 싶습니다 :)

1

1377

1

DatabaseSessionHandler.php 에러 해결 부분

0

299

1

안녕하세요. 라우터 서버 연결 질문이 있습니다.

1

281

1

아니 강사님 왜 자꾸 어어 거려요? 진짜 겁나 거슬려 죽겠네 ㅡㅡ 어좀 적당히해요 거슬려 죽겠네 그리고 마이크 좀 좋은거 쓰세요 볼륨이 낮아졌다 커졌ㄷ ㅏ하고 발음도 다뭉개져지고 딕션도 안 좋아서 하나도 안들려요 진짜 개짜증나네

1

574

2

로컬환경에서 개발 후 운영환경으로 배포 시 발생하는 이슈에 대한 문의입니다.

1

575

2

DatabaseSessionHandler 클래스의 gc($maxlifetime) 메소드에 대해 질문드립니다.

2

259

1

Xdebug 설치 후 php index.php 실행하면 오류가 납니다..!

0

1135

1

CentOS 7.* 서버쪽으로 배포를 해보던 중에 질문드립니다.

1

371

1

User 클래스에 대한 질문입니다.

1

187

1