11 April 2016

目录结构

src/
  Business.php
  Person.php
  Staff.php
index.php       <== 这个文件主要用来调用上面三个类

创建所需要的文件

➜ mkdir src
➜ touch src/Business.php
➜ touch src/Person.php
➜ touch src/Staff.php
➜ touch index.php

Business.php

<?php

class Business {

    protected $staff;

    public function __construct(Staff $staff) {
        $this->staff = $staff;
    }

    public function hire(Person $person) {
        $this->staff->add($person);
    }

    public function getStaffMembers() {
        return $this->staff->members();
    }
}

Person.php

<?php

class Person {
    protected $name;

    public function __construct($name) {
        $this->name = $name;
    }
}

Staff.php

<?php

class Staff {
    protected $members = [];

    public function __construct($members = []) {
        $this->members = $members;
    }

    public function add(Person $person) {
        $this->members[] = $person;
    }

    public function members() {
        return $this->members;
    }
}

index.php

// require './src/Person.php';
// require './src/Staff.php';
// require './src/Business.php';

function __autoload($name) {
    require './src/'.$name.'.php';
}

$user1    = new Person('user one');
$staff    = new Staff([$user1]);
$business = new Business($staff);

$business->hire(new Person('user two'));

var_dump($business->getStaffMembers());

执行 php index.php, 是可以正常访问的

结合 composer

➜ touch composer.json
➜ composer install

➜ vi composer.json
{
    "autoload": {
        "psr-4": {
            "myNamespace\\": "src"
        }
    }
}

一定要写 psr-4, myNamespace (对应的命名空间) 和 src (文件路径)

然后给 4 个 php 文件分别添加 namespace myNamespace;, index.php 再载入 autoload 文件

以 index.php 为例,其他文件也是需要添加 namespace myNamespace;

<?php

namespace myNamespace;

require './vendor/autoload.php';

$user1 = new Person('user one');
$staff = new Staff([$user1]);
$business = new Business($staff);

$business->hire(new Person('user two'));

var_dump($business->getStaffMembers());

执行 php index.php 可以正常访问

再次测试

创建 User 目录, 将 Person.php 移动到 User 目录里面

➜ mkdir src/User
➜ mv src/Person.php src/User

执行 php index.php 不能正常访问

修改 Person.php 的命名空间引入

Person.php

namespace myNamespace\User;       <== 这里的 User 就是它的目录

index.php

use myNamespace\User\Person;

Business.php

use myNamespace\User\Person;

Staff.php

use myNamespace\User\Person;

执行 php index.php, 成功