PHP: autoload problem

I am building a website and I am using Apache as my web server.

I created a site without using classes. All my functions are located in one file, and I just include this file on every page where I need to use some of the functions.

Now I want to switch to the OOP approach, but it's hard for me to figure out how to automatically load my classes. I went through a series of related pages, for example; PSR-4 example , spl_autoload_register () , A related question , and I just can't seem to think about it.

So, when I use Apache, the path for the root of my site is C: \ Apache \ htdocs .

My directories look like this:

+ htdocs
    + Lib
        + Base
            - User.php
            - Device.php
            - Company.php
            - Database.php
        + Services
            - UserService.php
            - DeviceService.php
            - CompanyServer.php
        + Config
            - DbConfig.php

, , DbConfig .

DbConfig.php ( )

<?PHP
namespace Lib\Config;

class DbConfig
{
    protected $serverName;
    protected $userName;
    protected $password;
    protected $dbName;

   public function __construct()
    {
        $this->serverName = 'not my server name';
        $this->userName = 'not my username';
        $this->passCode = 'not my password';
        $this->dbName = 'not my database';
    }
}

Database.php ( , ),

<?PHP
namespace Lib\Base;

use Lib\Config\DbConfig;

class Database extends DbConfig
{
    protected $connection;
    private $dataSet;
    private $sqlQuery;

    public function __construct()
    {
        parent::__construct();      
        $this->connection = null;
        $this->dataSet = null;
        $this->sqlQuery = null;
    }
}

..

  • , spl_autoload_register(), .php, ? , " Testing.php"

  • .ini , , , class DbConfig?

+4
3

PSR-4,

, " ".

, , . , namespace Lib\Config; , , namespace AskMeOnce\Lib\Config;. .

, PSR-4, , $prefix = 'Foo\\Bar\\'; $prefix = 'AskMeOnce\\'; $base_dir = __DIR__ . '/src/'; $base_dir = 'C:\Apache\htdocs';. autoload.php , , .

, require , PHP , , AskMeOnce . . , AskMeOnce\Lib\Config\DbConfig <basedir>/Lib/Config/DbConfig.php.

, (1) autoload.php , . (2), ini PHP, , , , ( ).

+1

, :

autoloader.php. PSR-4. Acme .

, Lib/, ( ).

<?php
/**
 * An example of a project-specific implementation.
 * @param string $class The fully-qualified class name.
 * @return void
 */
spl_autoload_register(function ($class) {

    // project-specific namespace prefix
    $prefix = 'Acme\\';

    // base directory for the namespace prefix
    $base_dir = __DIR__ . '/Lib/';

    // does the class use the namespace prefix?
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        // no, move to the next registered autoloader
        return;
    }

    // get the relative class name
    $relative_class = substr($class, $len);

    // replace the namespace prefix with the base directory, replace namespace
    // separators with directory separators in the relative class name, append
    // with .php
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
    print $file;
    // if the file exists, require it
    if (file_exists($file)) {
        require $file;
    }
});

spl_autoload_register /, PRS-4.

, Database Lib/Base/Database.php.

<?php

namespace Acme\Base;

class Database
{
    private $db;

    public function __construct(\PDO $db)
    {
        $this->db = $db;
    }

    public function allUsers()
    {
        /*
         * Query to fetch all users from the database
         */

        return [
            [
                'username' => 'Bob',
                'role' => 'member'
            ],
            [
                'username' => 'Joe',
                'role' => 'admin'
            ]
        ];
    }
}

, , autoloader.php script, .

<?php

require_once 'autoloader.php';

$config = require 'config.php';

try {
    $dbc = new PDO("mysql:dbname={$config['MYSQL']['DATABASE']};host={$config['MYSQL']['HOST']}",
                   $config['MYSQL']['USERNAME'], $config['MYSQL']['PASSWORD']);
} catch (PDOException $e) {
    die('Could not connect to database ' . $e->getMessage());
}

$db = new \Acme\Database($dbc);
print_r($db->allUsers());

, , . :

<?php

return [
    'MYSQL' => [
        'USERNAME' => 'root',
        'PASSWORD' => '',
        'DATABASE' => 'test',
        'HOST' => 'localhost'
    ]
];

:

$config = require 'config.php';

:

$config['MYSQL']['USERNAME'];

\PDO Database . Injection of Dependency.

: Lib/Services/UserService.php:

<?php

namespace Acme\Services;

class UserService
{
    ...
}

( ):

$userService = new \Acme\Services\UserService;

Composer. , Packagist, . PSR- * ( PSR4).

+1

register autoload function:

add code to any file that may be included before using other classes of the php library, for example, in the project input file.

defined('ROOT') or define('ROOT', 'C:/Apache/htdocs');
// define root directory
// or `defined('ROOT') or define('ROOT', __DIR__)` if
// the file is in the root directory

spl_autoload_register(function($name) {
    $file = ROOT . "/{$name}.php";
    if(!is_file($file)) {
        return false;
    } else {
        return include $file;
    }
}, false, true);

it is not recommended to use a namespace if your project is not large enough, just use the directory and file name for this

0
source

Source: https://habr.com/ru/post/1629906/


All Articles