Zend Framework 2 - How to use an external library

2019-01-19 09:11发布

问题:

I want to add my custom class "Authentication.php" to my project but I don't understand how I have to do it ?

I have read many howto about the external libs but nothing work.

ZendFramework/module/Firewall/Module.php

class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                    'MyNamespace' => __DIR__ . '/../../vendor/MyNamespace/lib/MyNamespace',
                ),
            ),
        );
    }
}

ZendFramework/vendor/MyNamespace/lib/MyNamespace /Authentication.php

<?php

class Authentication {

public function test()
{
     die('Work fine');
}


}

?>

How I can call my external lib in my controllers.

Thanks you very much !

回答1:

I try like this:

1)

//module/Application/Module.php
public function getAutoloaderConfig()
{
    return array(
        'Zend\Loader\StandardAutoloader' => array(
            'namespaces' => array(
                __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                'Mynamespace' => __DIR__ . '/../../vendor/Mynamespace',
            ),
        ),
    );
}

2)

//vendor/Mynamespace/MyClass.php
namespace Mynamespace;
class MyClass
{
    //...
}

3) I use it, for example in my controller:

use Zend\Mvc\Controller\AbstractActionController;
use Mynamespace\MyClass;
class AdminController extends AbstractActionController
{
    public function indexAction()
    {
        $myclass = new MyClass();
    }
}


回答2:

For this kind of library, just type in your application.config.php

<?php
return array(
    'modules' => array(
        'ZendDeveloperTools',
        'Application',
        'YourLibrary' // <-- here
        ...


回答3:

in composer.json file add the library as below

 "require": {
            "php": ">=5.3.3",
            "zendframework/zendframework": ">2.2.0rc1",
            "doctrine/doctrine-orm-module": "0.7.*",
            "zendframework/zend-developer-tools": "dev-master",
            "twig/twig": ">=1.12.3",

        }

Then in your application.config.php under the modules array

'modules' => array(
        'Application',
            'ZendDeveloperTools',
            'ZfcTwig',
            'DoctrineModule',
            'DoctrineORMModule','yourdir',

    ),

So do something similar to it.