Skip to content

Instantly share code, notes, and snippets.

@brzuchal
Last active April 18, 2018 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brzuchal/15b45556ae38df63a8ef3abd46062a9a to your computer and use it in GitHub Desktop.
Save brzuchal/15b45556ae38df63a8ef3abd46062a9a to your computer and use it in GitHub Desktop.
PHP Packages
<?php
require 'autoload.php';
$someObject = new Vendor\Package\SomeClass(); // autoloader tries to load... what exactly??? need to load vendor package.php somehow
<?php
require 'autoload.php';
use Vendor\Package\*; // this loads package, calls Vendor\Package\__init() and imports known public symbols
echo Vendor\Package::package; // 'Vendor\Package'
new Vendor\Package(); // throws fatal error while it's not a class
my_function();
echo my_function::function; // 'Vendor\Package\my_function'
echo my_function::package; // 'Vendor\Package'
$myObject = new MyClass();
$myOtherObject = new MyOtherClass();
$myNonExistingClass new Vendor\Package\NonExistingClass(); // throws fatal error, class not found
$myPrivateClass = new MyPrivateClass(); // throws fatal error, class not found
$myPublicObject = new MyPublicClass(); // 'Hello <Vendor\Package\MyPublicClass inside Vendor\Package>'
<?php
package Vendor\Package;
public class MyClass, MyOtherClass; // those two classes will be imported by default using *
public function my_function; // this function will be imported by default using *
// this is called at first attempt to the package
public function __init()
{
if (extension_loaded('spl')) {
throw Exception(self::package . ' highly depends on "spl" extension which is not loaded');
}
if (package_exists(\Symfony\Component\Console::package)) {
throw Exception(self::package . ' highly depends on "symfony/console" package which is available');
}
// register package loader
(new Psr4Loader())->add(self::package, 'src')->register();
require __DIR__ . '/src/functions.php'; // import some symbols
require __DIR__ . '/src/SomeBunchOfClasses.php'; // import some class symbols
}
// this class will be imported by default using *
public class MyPublicClass
{
public function __construct()
{
echo 'Hello <' . self::class . ' inside ' . self::package . '>';
}
}
// this class won't be imported and won't be accessible outside package
private class MyPrivateClass
{
}
<?php
package Vendor\Package; // this autoloads package and calls Vendor\Package\__init()
// class is not marked as private so it'll be public by default
class SomeClass
{
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment