Libraries loader php joomla

Cognitive Complexity

Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

A method’s cognitive complexity is based on a few simple rules:

  • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
  • Code is considered more complex for each «break in the linear flow of the code»
  • Code is considered more complex when «flow breaking structures are nested»

Further reading

Method import has 34 lines of code (exceeds 25 allowed). Consider refactoring.

 public static function import($key, $base = null) < // Only import the library if not already attempted. if (!isset(self::$imported[$key])) 

Function discover has a Cognitive Complexity of 11 (exceeds 5 allowed). Consider refactoring.

 public static function discover($classPrefix, $parentPath, $force = true, $recurse = false) < try < if ($recurse)

Cognitive Complexity

Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

A method's cognitive complexity is based on a few simple rules:

  • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
  • Code is considered more complex for each "break in the linear flow of the code"
  • Code is considered more complex when "flow breaking structures are nested"

Further reading

Method discover has 29 lines of code (exceeds 25 allowed). Consider refactoring.

 public static function discover($classPrefix, $parentPath, $force = true, $recurse = false) < try < if ($recurse)

Function loadByNamespaceMixedCase has a Cognitive Complexity of 10 (exceeds 5 allowed). Consider refactoring.

 public static function loadByNamespaceMixedCase($class) < // If the class already exists do nothing. if (class_exists($class, false)) 

Cognitive Complexity

Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

A method's cognitive complexity is based on a few simple rules:

  • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
  • Code is considered more complex for each "break in the linear flow of the code"
  • Code is considered more complex when "flow breaking structures are nested"

Further reading

Method setup has 27 lines of code (exceeds 25 allowed). Consider refactoring.

 public static function setup($caseStrategy = self::LOWER_CASE, $enableNamespaces = false, $enablePrefixes = true, $enableClasses = true) < if ($enableClasses) < // Register the class map based autoloader.

Function setup has a Cognitive Complexity of 8 (exceeds 5 allowed). Consider refactoring.

 public static function setup($caseStrategy = self::LOWER_CASE, $enableNamespaces = false, $enablePrefixes = true, $enableClasses = true) < if ($enableClasses) < // Register the class map based autoloader.

Cognitive Complexity

Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

A method's cognitive complexity is based on a few simple rules:

  • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
  • Code is considered more complex for each "break in the linear flow of the code"
  • Code is considered more complex when "flow breaking structures are nested"

Further reading

Function loadByNamespaceNaturalCase has a Cognitive Complexity of 7 (exceeds 5 allowed). Consider refactoring.

 public static function loadByNamespaceNaturalCase($class) < // If the class already exists do nothing. if (class_exists($class, false)) 

Cognitive Complexity

Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

A method's cognitive complexity is based on a few simple rules:

  • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
  • Code is considered more complex for each "break in the linear flow of the code"
  • Code is considered more complex when "flow breaking structures are nested"

Further reading

Function loadByNamespaceLowerCase has a Cognitive Complexity of 7 (exceeds 5 allowed). Consider refactoring.

 public static function loadByNamespaceLowerCase($class) < // If the class already exists do nothing. if (class_exists($class, false)) 

Cognitive Complexity

Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

A method's cognitive complexity is based on a few simple rules:

  • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
  • Code is considered more complex for each "break in the linear flow of the code"
  • Code is considered more complex when "flow breaking structures are nested"

Further reading

Similar blocks of code found in 2 locations. Consider refactoring.

 public static function registerNamespace($namespace, $path, $reset = false) < // Verify the library path exists. if (!file_exists($path)) 

Duplicated Code

Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).

Tuning

This issue has a mass of 117.

We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.

The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.

If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.

See codeclimate-duplication 's documentation for more information about tuning the mass threshold in your .codeclimate.yml .

Refactorings

Further Reading

Similar blocks of code found in 2 locations. Consider refactoring.

 public static function registerPrefix($prefix, $path, $reset = false) < // Verify the library path exists. if (!file_exists($path)) 

Источник

Подключаем свою библиотеку при разработке расширений

Подключаем свою библиотеку при разработке расширений

В статье "Техники быстрой разработки: предотвращение фрагментации кода в Joomla" был рассмотрен метод подключения файлов из своей библиотеки при помощи jimport . Он работает, но имеет два недостатка:

  • внесение изменения в файл ядра loader.php
  • необходимость при каждом подключении файла писать jimport

Обойти эти недостатки нам поможет класс JLoader. Он предоставляет возможность подключать отдельные классы и целые библиотеки с помощью автозагрузчика классов Joomla. Предположим, что файлы вашей библиотеки расположены в /libraries/mylib . Давайте рассмотрим различные способы использования автозагрузчика для подключения классов из нашей библиотеки и облегчения работы при разработке расширений.

Регистрация классов

С помощью метода register() вы можете добавить конкретный класс в автозагрузчик:

JLoader::register('MylibUser', JPATH_LIBRARIES . '/mylib/user.php');

Теперь в любой точки вашего расширения вы можете обратиться к классу MylibUser без необходимости явного подключения вроде jimport или require_once .

Поиск классов

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

// Регистрируем все файлы в папке /libraries/mylib как классы с именем Mylib JLoader::discover('Mylib', JPATH_LIBRARIES . '/mylib');

Как видите, этот метод работает, если вы следуете определенному именованию файлов и классов:

/mylib/user.php равно классу MylibUser
/mylib/userhelper.php равно классу MylibUserHelper
и т.д.

Дополнительные аргументы позволяют обновить путь уже зарегистрированного класса и рекурсивно пройтись по поддиректориям:

// Регистрируем все файлы в папке /libraries/mylib, а также в подпапках как классы с именем Mylib JLoader::discover('Mylib', JPATH_LIBRARIES . '/mylib', false, true);

Загрузка классов через регистрацию префикса

Начиная с версии Joomla Platform 12.1 (Joomla CMS 3+) существует возможность зарегистрировать префикс класса, по которому автозагрузчик будет искать классы вашей библиотеки (до этого была поддержка только префикса "J", который привязан к папке /libraries/joomla ). Это позволяет нам сделать следующее:

  • зарегистрировать префикс своих классов и корневой путь до них;
  • зарегистрировать дополнительный путь для существующего префикса (например, это позволяет Joomla CMS использовать дополнительные библиотеки, при этом используя префикс "J");
  • зарегистрировать переопределение префикса. Это может быть использовано для переопределения базовых классов.

Чтобы использовать метод registerPrefix() необходимо следовать определенному соглашению по именованию классов и файлов. Имя класса должно быть в camel case, где каждый сегмент имени представляет путь к папке, а последний сегмент является именем файла класса. Если в имени класса только одна часть, то автозагрузчик будет искать файл в папке с таким же названием. Названия папок должны быть в нижнем регистре.

Класс PrefixUserModel должен находиться в ПУТЬ_ДО_ПРЕФИКСА/user/model.php
Класс PrefixUser должен находиться в ПУТЬ_ДО_ПРЕФИКСА /user/user.php

Применительно к нашему примеру:

Класс MylibUserHelper должен находиться в /libraries/mylib/user/helper.php
Класс MylibUser должен находиться в /libraries/mylib/user/user.php

// Ищем классы, начинающиеся с "Mylib" в папке /libraries/mylib. JLoader::registerPrefix('Mylib', JPATH_LIBRARIES . '/mylib');
// Ищем классы с префиксом "J" дополнительно в папке /libraries/cms. JLoader::registerPrefix('J', JPATH_PLATFORM . '/cms');
// Сбрасываем префикс "J" и указываем на свой форк платформы. JLoader::registerPrefix('J', '/my/platform/fork', true);

Обратите внимание на то, что такие акронимы как HTML, XML и MySQL в названиях классов тоже должны придерживаться соглашения camel case: HTML становится Html, XML становится Xml и т.д.

Доступ к библиотеке из любой точки Joomla

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

class plgSystemMylib extends JPlugin < public function onAfterInitialise() < JLoader::registerPrefix('Mylib', JPATH_LIBRARIES . '/mylib'); >>

Все просто – после инициализации приложения мы регистрируем наш префикс, и автозагрузчик начинает работать на нас. Теперь в любой точке приложения, будь то модуль, компонент или плагин мы можем получить доступ к классам из нашей библиотеки. Пример полного плагина можно увидеть здесь.

Источник

Читайте также:  Как долго учиться html
Оцените статью