Pular para o conteúdo

Plugins de terceiros

O 4SEF constrói os URLs SEF de um componente específico através de um código dedicado, feito à medida desse componente. Inclui suporte para todos os tipos de conteúdo nativos do Joomla, bem como para algumas extensões de terceiros muito utilizadas.

Para os componentes sem plugin de suporte específico, o 4SEF recorre ao próprio ficheiro router.php do componente, normalmente destinado a ser utilizado pelo sistema de URLs SEF do Joomla. Este processo é automático e funciona na maioria dos casos.

Se pretender fornecer um conjunto de URLs mais apurado para um componente que utiliza ou que construiu, pode criar um driver de URLs SEF para o 4SEF.

Um driver é, no mínimo, um único ficheiro de classe PHP, que pode guardar onde quiser. Pode fazer parte do seu próprio componente, por exemplo, ou estar dentro de um plugin dedicado (ver o parágrafo abaixo, Carregar o seu driver).

O driver estende uma classe base fornecida pelo 4SEF e tem 3 funções principais:

  • construir o URL SEF a partir das variáveis não-SEF, de forma semelhante ao próprio ficheiro router.php do Joomla
  • construir o URL não-SEF “normalizado”. A maior parte disso já é feita pelo 4SEF, mas poderá querer remover algumas variáveis de consulta específicas do componente.
  • opcionalmente, determinar se um URL SEF deve ser deixado como não-SEF, o que por vezes é prático e poupa espaço
<?php
/**
* Project: 4SEF
*
* @package 4SEF
* @copyright Copyright Weeblr llc - 2022
* @author Yannick Gaultier - Weeblr llc
* @license GNU General Public License version 3; see LICENSE.md
* @version 1.0.0
* @date 2022-06-03
*/
namespace Weeblr\Forsef\Platform\Extensions;
use Joomla\CMS\Uri;
use Weeblr\Forsef\Data;
use Weeblr\Forsef\Helper;
use Weeblr\Wblib\Forsef\Wb;
use Weeblr\Wblib\Forsef\System;
use Weeblr\Wblib\Forsef\Factory;
// no direct access
defined('_JEXEC') || die();
/**
* Sample plugin to build URL for a com_sample component.
*
* - Drop the "com_" at the start from the component to name the class
* - Below are only the most important methods. For more advanced logic,
* be sure to check the built-in plugins in
*
* /plugins/system/forsef/platform/extensions
*
*/
class Sample extends Base
{
/**
* @var Helper\Platform
*/
private $platformHelper;
/**
* Stores factory instance.
*
* @param string $option Extension this applies to, in com_xxx format.
* @param array $options Can inject custom factory and platform.
*/
public function __construct($option, $options = [])
{
parent::__construct($option, $options);
$this->platformHelper = $this->factory
->getA(Helper\Platform::class);
}
/**
* Builds the SEF URL for a non-sef.
*
* @param Uri\Uri $uriToBuild
* @param Uri\Uri $platformUri
* @param Uri\Uri $originalUri
*
* @return \array
* @throws \Exception
*/
public function build($uriToBuild, $platformUri, $originalUri)
{
$sefSegments = parent::build($uriToBuild, $platformUri, $originalUri);
// Read whatever variables you need to build your SEF URL.
$view = $uriToBuild->getVar('view');
$layout = $uriToBuild->getVar('layout');
$id = $uriToBuild->getVar('id');
$Itemid = $uriToBuild->getVar('Itemid');
// and add strings to the $sefSegments array to build the URL.
// $sefSegments[] = 'something'
// Add a / as the last element of the sefSegments array to prevent the
// .html suffix to be appended to the URL later on (if set in 4SEF configuration).
// $sefSegments[] = '/';
return $sefSegments;
}
/**
* Participate in building a normalized non-sef URL based on an incoming URI. Query vars values are URL-encoded.
* Stripping slugs, sorting vars and possibly other things are taken care globally. Only plugin-specific
* vars processing should happen here. For instance, stripping pagination variables if the plugin
* handles pagination dynamically.
*
* @param array $vars
* @return array
*/
public function buildNormalizedNonSef($vars)
{
return $this->nonSefHelper->stripFeedVars(
parent::buildNormalizedNonSef(
$vars
)
);
}
/**
* Check if passed URI is for an extension configured to be left non-sef.
*
* @param Uri\Uri $uriToBuild
* @return bool
*/
public function shouldLeaveNonSef($uriToBuild)
{
// read whatever variables you need to decide whether a
// URL must be left non-sef
$view = $uriToBuild->getVar('view');
$task = $uriToBuild->getVar('task');
$layout = $uriToBuild->getVar('layout');
$a_id = $uriToBuild->getVar('a_id');
// then check these variables and return true
// if this URL must be left non-sef.
// by default, all URLs are made SEF
return false;
}
}

Como o seu driver é apenas uma classe PHP específica, o 4SEF deteta-o e utiliza-o automaticamente quando necessário, desde que este ficheiro PHP seja incluído uma vez.

Existem 3 formas de o fazer, descritas abaixo. Sugerimos que construa um verdadeiro plugin Joomla para envolver o seu driver: é a forma mais prática para os utilizadores finais, para as atualizações, etc., embora as 3 opções sejam perfeitamente viáveis.

Pode simplesmente fazer um include_once 'my_4sef_driver.php' em qualquer ponto da sua própria extensão para tornar o driver disponível. Se tiver o nome correto (ver o exemplo acima), o 4SEF consegue detetá-lo e utilizá-lo.

Responder ao evento de carregamento dos plugins do 4SEF

Seção intitulada “Responder ao evento de carregamento dos plugins do 4SEF”

Imediatamente antes de precisar de construir o seu primeiro URL SEF, o 4SEF aciona um evento que lhe permite incluir o seu driver. Pode carregar o seu driver adicionando o seguinte código à sua extensão:

<?php
// Your extension own code here
// Include use statement for 4SEF factory class
use Weeblr\Forsef\Factory as ForsefFactory;
// somewhere in your extension, add the following to respond to 4SEF event:
ForsefFactory::get()->getThe('hook')->add(
'forsef_on_load_plugins',
function () {
// include your plugin file here
// Sample code to include your driver
$filename = '/absolute/path/to/your/driver/componentname.php';
if (file_exists($filename))
{
include_once $filename;
}
}
);

Pode construir um verdadeiro plugin Joomla para envolver e distribuir o seu driver aos utilizadores. Na verdade, é bastante simples, e trata de carregar o seu driver suficientemente cedo.

Eis a estrutura de um plugin deste tipo:

Estrutura de pastas de um plugin de URLs do 4SEF

O ficheiro /plugin/sample.php contém o seu driver, tal como descrito no parágrafo Exemplo de código de um driver acima.

Eis o ficheiro de manifesto, sample.xml:

<?xml version="1.0" encoding="utf-8"?>
<extension type="plugin" group="forsef" method="upgrade">
<name>PLG_FORSEF_SAMPLE</name>
<author>Yannick Gaultier - Weeblr llc</author>
<creationDate>2022-06-03</creationDate>
<copyright>Copyright Weeblr llc - 2022</copyright>
<license>GNU General Public License version 3; see LICENSE.md</license>
<authorEmail>[email protected]</authorEmail>
<authorUrl>https://weeblr.com/</authorUrl>
<version>1.0.0</version>
<description>PLG_FORSEF_SAMPLE_XML_DESCRIPTION</description>
<files>
<filename plugin="sample">sample.php</filename>
<folder plugin="sample">plugin</folder>
</files>
</extension>

e eis o ficheiro principal do plugin Joomla, sample.php:

<?php
/**
* Project: 4SEF
*
* @package 4SEF
* @copyright Copyright Weeblr llc - 2022
* @author Yannick Gaultier - Weeblr llc
* @license GNU General Public License version 3; see LICENSE.md
* @version 1.0.0
* @date 2022-06-03
*/
defined('_JEXEC') or die;
use Weeblr\Forsef\Factory as ForsefFactory;
use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\Event\DispatcherInterface;
/**
* 4SEF - A loader for a 4SEF SEF URL plugin.
*
* @since 1.0.0
*/
class PlgForsefSample extends CMSPlugin
{
/**
* @var string location of plugin file from
*/
private $pluginFileName = '/plugin/sample.php';
/**
* Constructor
*
* @param DispatcherInterface &$subject The object to observe
* @param array $config An optional associative array of configuration settings.
* Recognized key values include 'name', 'group', 'params', 'language'
* (this list is not meant to be comprehensive).
*
* @since 1.5
*/
public function __construct(&$subject, $config = array())
{
parent::__construct($subject, $config);
ForsefFactory::get()->getThe('hook')->add(
'forsef_on_load_plugins',
function () {
$filename = __DIR__ . $this->pluginFileName;
if (file_exists($filename))
{
include_once $filename;
}
}
);
}
}