Php include library in class

How do I include a PHP library?

In Drupal 7, there are hook_library() and drupal_add_library() that can be used to manage JavaScript and CSS libraries. I am looking for how to include the PHPExel library (now moved on GitHub) in my distribution. How can I achieve this?

3 Answers 3

hook_library() is thought only for Javascript and CSS files; for PHP libraries, you should consider the Libraries API module.

This module introduces a common repository for libraries in sites/all/libraries resp. sites//libraries for contributed modules.

External libraries

Denotes libraries («plugins») that are neither shipped nor packaged with a project on drupal.org. We do not want to host third-party libraries on drupal.org for a multitude of reasons, starting with licensing, proceeding to different release cycles, and not necessarily ending with fatal errors due to conflicts of having the same library installed in multiple versions. Drupal 7 only has built-in support for non-external libraries via hook_library() . But it is only suitable for drupal.org projects that bundle their own library; i.e., the module author is the creator and vendor of the library. Libraries API should be used for externally developed and distributed libraries. A simple example would be a third-party jQuery plugin.

The Libraries API module implements an API that can be used from third-party modules to load libraries installed on a Drupal site; the pro of using Library API is that it handles dependencies between libraries, and versioning.

The documentation explains which files can be loaded from a library defined using the Libraries API hooks. In particular, the documentation for hook_libraries_info() explains that, if $libraries is the value returned from the hook implementation, $libraries[‘files’][‘php’] is an array containing a list of PHP files that will be loaded when the library is loaded.
The Grammar Parser Library module defines a PHP library in gplib_libraries_info() .

function gplib_libraries_info() < $libraries['grammar_parser'] = array( 'title' =>'Grammar Parser Library', 'vendor url' => 'http://drupal.org/project/grammar_parser', 'download url' => 'http://drupal.org/project/grammar_parser', 'version arguments' => array( 'file' => 'CHANGELOG.txt', 'pattern' => '/pgp \(grammar parser\) (\d+\.x-\d+\.x)/', ), 'versions' => array( '7.x-1.x' => array(), ), 'files' => array( 'php' => array( 'engine/parser.inc', 'engine/editor.inc', 'engine/list.inc', 'engine/object.inc', 'engine/reader.inc', 'engine/writer.inc', ), ), ); return $libraries; > 

Источник

Базовые возможности PHP

При разработке программ на PHP, возможно, какую-ту часть кода мы захотим использовать одновременно в других файлах с кодом PHP. В этом случае отдельные части кода можно распределить по отдельным файлам. Это позволить не писать один и тот же код по сто раз на сотнях скриптов, а будет достаточно подключить файл с кодом PHP. Кроме того, если потребуется изменить поведение подключаемого кода, достаточно будет изменить код в подключаемом файле.

Читайте также:  Анимация появления div css

Для подключения файлов PHP предоставляет ряд возможностей.

Инструкция include

Инструкция include подключает в программу внешний файл с кодом php. Так, для примера определим файл welcome.php :

Здесь определена функция welcome , которая в качестве параметра принимает условное имя и использут его для вывода приветствия.

Теперь подключим данный файл в нашу программу, которая определена в другом файле в той же папке:

В место определения инструкции include будет вставляться весь код из файла welcome.php . При этом вставка файла должна происходить до использования функции, определенной в этом файле. При этом в данном случае файл welcome.php и файл, в который он подключается, располагаются в одной папке.

Конструкция include может использовать как относительные, так и абсолютные пути. Например, выше использовался относительный путь. Или, к примеру, если мы имеем следующую структуру

То чтобы подключить файл welcome.php из папки scripts , в файле index.php необходимо использовать следующий относительный путь:

include "scripts/welcome.php";

Если файл welcome.php располагается по полному пути C:\localhost\scripts\welcome.php , то также можно было бы использовать абсолютный — полный путь:

include "C:\localhost\scripts\welcome.php";

Инструкция include_once

Использование инструкции include имеет недостатки. Так, мы можем в разных местах кода неумышленно подключить один и тот же файл, что при выполнении кода вызовет ошибки.

Чтобы исключить повторное подключение файла, вместо инструкции include следует применять инструкцию include_once

И теперь, если мы подключим этот же файл с помощью include_once еще где-нибудь ниже, то это подключение будет проигнорировано, так как файл уже подключен в программу.

Инструкции require и require_once

Действие инструкции require подобно инструкции include: она также подключает внешний файл, вставляя в программу его содержимое. Только теперь, если данный файл не будет найден, действие программы прекратится (инструкция include в этом случае выбрасывает предупреждение):

И также если у нас в коде встретятся несколько инструкций require , которые подключают один и тот же файл, то интерпретатор выдаст ошибку. И также чтобы избежать данной ситуации, следует использовать инструкцию require_once :

Функция spl_autoload_register

В больших приложениях количество подключаемых файлов может быть довольно большим. Однако встроенная функция spl_autoload_register() в определенных ситуациях позволяет избежать большого количества инклудов. В качестве параметра она принимает функцию автозагрузки. Эта функция автоматически вызывается, когда в программе начинает использоваться неизвестный класс или интерфейс. И функция автозагруки пытается загрузить этот класс или интерфейс. В качестве параметра функция автозагрузки принимает название класса или интерфейса, которые надо загрузить.

Читайте также:  Блочные элементы

Например, пусть у нас будет файл Person.php , в котором располагается класс Person :

name = $name; $this->age = $age; > function printInfo() < echo "Name: $this->name
Age: $this->age"; > > ?>

Обращаю внимание, что название файла соответствует названию класса.

Используем функцию автозагрузки для подключения подобного класса:

"; include $class . ".php"; > spl_autoload_register("my_autoloader"); $tom = new Person("Tom", 25); $tom->printInfo(); ?>

Функция spl_autoload_register() в качестве параметра принимает название функции автозагрузки — в данном случае это функция my_autoloader() . В качестве параметра она принимает название класса. Например, в данном случае используется класс Person, который в этом скрипте не определен. И когда программа встретит использование данного класса, она вызовет функцию my_autoloader() , в качестве параметра $class передаст в нее название класса Person.

Все действия функции автозагрузки мы определяем сами. В данном случае с помощью echo выводится некоторое диагностическое сообщение и подключается файл класса:

При этом в данном случае неважно какой класс, главное, чтобы он хранился в одноименном файле с расширением .php . В этом случае программа выведет следующее:

Вызов функции автозагрузки Name: Tom Age: 25

Источник

Best practice for third-party PHP class-based library

to my .info file and let the Drupal 7 class auto loader do its thing when I do a $foo = new Foo() . I have permission, though, to release this module to the public and would rather not include the library with the module. I am well aware about the complications regarding licensing, but for the sake of this question, I would like to ignore it. There is a similar question, How do I include a PHP library?, but I don’t really think this answers my dilema. This answers to this question essentially say to use the Libraries API, but every single module that I have found that uses this just does a libraries_get_path() to get the basepath (and includes fallback path when it isn’t available) and then does a require or include with some error checking (or not). All do something like:

In this case, the Libraries API isn’t really doing anything. I don’t see the advantage to using this, over the old method of asking users to download a copy and place it in the module folder itself. And, there is still the issue that the module developer still needs to manually do the load with include / require . For example, the Facebook module just loads the library in a hook_init and the HTML Purifier module has an internal function to check-and-load every time the library is needed. This may be a widespread practice, but it doesn’t seem like a best practice. Should my module take the initiative and declare a hook_libraries_info so I can use libraries_load(‘foo’) ? This, too, seems odd.

Читайте также:  Find list length java

Источник

How To Create A Php Include Library

A directory sites/all/libraries should have been created. If not, just create the libraries directory in sites/all/ now create your php includes director in the sites/all/libraries directory. Copy all your …

function gplib_libraries_info() < $libraries['grammar_parser'] = array( 'title' =>'Grammar Parser Library', 'vendor url' => 'http://drupal.org/project/grammar_parser', 'download url' => 'http://drupal.org/project/grammar_parser', 'version arguments' => array( 'file' => 'CHANGELOG.txt', 'pattern' => '/pgp \(grammar parser\) (\d+\.x-\d+\.x)/', ), 'versions' => array( '7.x-1.x' => array(), ), 'files' => array( 'php' => array( 'engine/parser.inc', 'engine/editor.inc', 'engine/list.inc', 'engine/object.inc', 'engine/reader.inc', 'engine/writer.inc', ), ), ); return $libraries; > < "require": < "phpoffice/phpexcel": "^1.8.2" >> < "require": < "phpoffice/phpspreadsheet": "^1.18" >>

Starting a New PHP Package The Right Way

We’ll use the index.php file for testing some stuff out from time to time, but mostly, we’ll be using PHPUnit to develop our library. For now, let’s add index.php to .gitignore to …

sites: - map: test.app to: /home/vagrant/Code/diffbot_lib - map: test2.app to: /home/vagrant/Code/diffbot_test git clone https://github.com/Swader/php_package_skeleton diffbot_lib < "name": "swader/diffbot_client", "description": "A PHP wrapper for using Diffbot's API", "keywords": [ "diffbot", "api", "wrapper", "client" ], "homepage": "https://github.com/swader/diffbot_client", "license": "MIT", "authors": [ < "name": "Bruno Skvorc", "email": "[email protected]", "homepage": "http://bitfalls.com", "role": "Developer" >], "require": < "php" : ">=5.5.0" >, "require-dev": < "phpunit/phpunit" : "4.*" >, "autoload": < "psr-4": < "Swader\\Diffbot\\": "src" >>, "autoload-dev": < "psr-4": < "Swader\\Diffbot\\Test\\": "tests" >>, "extra": < "branch-alias": < "dev-master": "1.0-dev" >> > "require": < "php" : ">=5.5.0", "guzzlehttp/guzzle": "~5.0" >, /** * Friendly welcome * * @param string $phrase Phrase to return * * @return string Returns the phrase passed in */ public function echoPhrase($phrase) < return $phrase; >> echoPhrase("It's working"); $token = xxxx; // approach 1 $api1 = new Diffbot($token); $api2 = new Diffbot($token); // approach 2 Diffbot::setToken($token); $api1 = new Diffbot(); $api2 = new Diffbot(); > else < self::validateToken($token); $this->instanceToken = $token; > > /** * Sets the token for all future new instances * @param $token string The API access token, as obtained on diffbot.com/dev * @return void */ public static function setToken($token) < self::validateToken($token); self::$token = $token; >private static function validateToken($token) < if (!is_string($token)) < throw new \InvalidArgumentException('Token is not a string.'); >if (strlen($token) < 4) < throw new \InvalidArgumentException('Token "' . $token . '" is too short, and thus invalid.'); >return true; > > 

Источник

Оцените статью