J3.x

J3.x:Developing an MVC Component/Adicionando uma view para o site.

From Joomla! Documentation

< J3.x:Developing an MVC Component
Revision as of 20:03, 28 August 2017 by FuzzyBot (talk | contribs) (Updating to match new version of source page)
Other languages:
Deutsch • ‎English • ‎Nederlands • ‎español • ‎français • ‎português do Brasil • ‎русский • ‎العربية • ‎中文(台灣)‎
Joomla! 
3.x
Tutorial
Desenvolvendo um Componente MVC

Adicionando uma requisição de variável no tipo de menu

Usando o Banco de Dados

Backend básico

Adicionando o gerenciamento de linguagem

Adicionando ações de backend

Adicionando decorations para o backend

Adicionando verificações

Adicionando categorias

Adicionando configuração

  1. Adicionando ACL (Lista de Controle de Acesso)

Adicionando um script de instalação/desinstalação/atualização

Adding a Frontend Form

  1. Adding an Image
  2. Adding a Map
  3. Adding AJAX
  4. Adding an Alias

Usando o recurso de filtro de idioma

  1. Adding a Modal
  2. Adding Associations
  3. Adding Checkout
  4. Adding Ordering
  5. Adding Levels
  6. Adding Versioning
  7. Adding Tags
  8. Adding Access
  9. Adding a Batch Process
  10. Adding Cache
  11. Adding a Feed

Adicionando um servidor de atualização

  1. Adding Custom Fields
  2. Upgrading to Joomla4



Esta é uma série de vários artigos de tutoriais sobre como desenvolver um Componente Model-View-Controller para o Joomla! VersionJoomla 3.x.

Comece com a Introdução, e navegue pelos artigos desta série usando o botão de navegação abaixo ou a caixa à direita ("Artigos desta série").



Notas

Este tutorial é parte do tutorial Desenvolvendo um Componente MVC para Joomla! 3.x. Recomendamos que você leias as partes anteriores desse tutorial antes de ler essa.

Você pode seguir os passos abaixo para criar o Hello World! , Ou você pode baixar diretamente o arquivo archive

  • As you follow through the steps of the tutorial you may find problems. In this case you may find it useful to read the Joomla page on How to debug your code.

Adicionando uma View para o Hello World!

Neste artigo, vamos abordar como adicionar uma view para um Componente Básico Joomla!. Para este exemplo, continuaremos nosso trabalho no componente Hello World!

Existem várias maneiras de atualizar um componente Joomla!. Neste tutorial focaremos a opção 2.

1 Adicionar manualmente os arquivos em <pasta_do_joomla>/
2 Atualizar usando o Gerenciador de Extensões Joomla! e o diretório original, não-compactado, usado para a instalação do componente
3 Atualizar usando o Joomla! Extension Manager e um Servidor de Atualização

Para adicionar uma view, você precisará navegar até com_helloworld , que é o diretório original que criamos para o nosso componente. Usando seu gerenciador de arquivos preferido, crie ou atualize os seguintes arquivos; À medida que você cria ou atualiza os arquivos, adicione o código-fonte para cada arquivo encontrado em Detalhes dos Arquivos.

1 Atualizar: helloworld.php <path_to_com_helloworld>/site/helloworld.php
2 Criar: controller.php <path_to_com_helloworld>/site/controller.php
3 Criar: index.html <path_to_com_helloworld>/site/views/index.html
4 Criar: index.html <path_to_com_helloworld>/site/views/helloworld/index.html
5 Criar: view.html.php <path_to_com_helloworld>/site/views/helloworld/view.html.php
6 Criar: default.php <path_to_com_helloworld>/sites/views/helloworld/tmpl/default.php
7 Criar: index.html <path_to_com_helloworld>/site/views/helloworld/tmpl/index.html
8 Atualizar: helloworld.xml <path_to_com_helloworld/helloworld.xml

Atualizando o Componente Hello World!

Para atualizar o Componente Hello World! no Joomla! Siga as mesmas etapas de Instalação Original.


Detalhes de Arquivos

site/helloworld.php (Note that some browsers may not copy and paste highlighted text correctly into a text editor. If you find this, then please try a different browser).

<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

// No direct access to this file
defined('_JEXEC') or die('Restricted access');

// Get an instance of the controller prefixed by HelloWorld
$controller = JControllerLegacy::getInstance('HelloWorld');

// Perform the Request task
$input = JFactory::getApplication()->input;
$controller->execute($input->getCmd('task'));

// Redirect if set by the controller
$controller->redirect();

site/controller.php

<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
/**
 * Hello World Component Controller
 *
 * @since  0.0.1
 */
class HelloWorldController extends JControllerLegacy
{
}

site/views/helloworld/view.html.php

<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

// No direct access to this file
defined('_JEXEC') or die('Restricted access');

/**
 * HTML View class for the HelloWorld Component
 *
 * @since  0.0.1
 */
class HelloWorldViewHelloWorld extends JViewLegacy
{
	/**
	 * Display the Hello World view
	 *
	 * @param   string  $tpl  The name of the template file to parse; automatically searches through the template paths.
	 *
	 * @return  void
	 */
	function display($tpl = null)
	{
		// Assign data to the view
		$this->msg = 'Hello World';

		// Display the view
		parent::display($tpl);
	}
}

site/views/helloworld/tmpl/default.php

<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */
 
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
?>
<h1><?php echo $this->msg; ?></h1>

index.html Notas - O mesmo código é usado para todos os diretórios.

<html><body bgcolor="#FFFFFF"></body></html>

helloworld.xml

<?xml version="1.0" encoding="utf-8"?>
<extension type="component" version="3.2.0" method="upgrade">

	<name>Hello World!</name>
	<!-- The following elements are optional and free of formatting constraints -->
	<creationDate>December 2013</creationDate>
	<author>John Doe</author>
	<authorEmail>john.doe@example.org</authorEmail>
	<authorUrl>http://www.example.org</authorUrl>
	<copyright>Copyright Info</copyright>
	<license>License Info</license>
	<!--  The version string is recorded in the components table -->
	<version>0.0.2</version>
	<!-- The description is optional and defaults to the name -->
	<description>Description of the Hello World component ...</description>

	<update> <!-- Runs on update; New since J2.5 -->
		<schemas>
			<schemapath type="mysql">sql/updates/mysql</schemapath>
		</schemas>
	</update>

	<!-- Site Main File Copy Section -->
	<!-- Note the folder attribute: This attribute describes the folder
		to copy FROM in the package to install therefore files copied
		in this section are copied from /site/ in the package -->
	<files folder="site">
		<filename>index.html</filename>
		<filename>helloworld.php</filename>
		<filename>controller.php</filename>
		<folder>views</folder>
	</files>

	<administration>
		<!-- Administration Menu Section -->
		<menu link='index.php?option=com_helloworld'>Hello World!</menu>
		<!-- Administration Main File Copy Section -->
		<!-- Note the folder attribute: This attribute describes the folder
			to copy FROM in the package to install therefore files copied
			in this section are copied from /admin/ in the package -->
		<files folder="admin">
			<!-- Admin Main File Copy Section -->
			<filename>index.html</filename>
			<filename>helloworld.php</filename>
			<!-- SQL files section -->
			<folder>sql</folder>
		</files>
	</administration>

</extension>

Explicação do código

No caso de você estar curioso para saber porque o código funciona e como ele funciona.

helloworld.php

defined('_JEXEC') or die('Restricted access');

Isso habilitar um ponto de entrada seguro na plataforma Joomla!. JEXEC contem uma explicação detalhada.

$controller = JControllerLegacy::getInstance('HelloWorld');

JControllerLegacy é a classe base para o controlador Joomla!. Para que o nosso site utilize controladores, nos precisamos extender essa classe em nosso componente. O método estático getInstance da classe JControllerLegacy irá criar um controller. No código acima, instanciará um objeto controller de uma classe chamada HelloWorldController. Joomla irá procurar pela declaração desta classe em <path_to_joomla>/htdocs/components/com_helloworld/controller.php.

$input = JFactory::getApplication()->input;
$controller->execute($input->getCmd('task'));

Após a criação do controller, instruímos o mesmo a executar a tarefa, conforme definido na URL: <yoursite> /joomla/index.php?option=com_helloworld&task= <task_name>. Se nenhuma tarefa for definida, a tarefa padrão 'display' será executada. Quando o display é usado, a variável 'view' irá decidir o que será exibido. Outras tarefas comuns são salvar, editar, novo, etc

$controller->redirect();

O controlador pode decidir redirecionar a página, geralmente depois que uma tarefa como 'salvar' foi concluída. Esta última instrução cuida do redirecionamento atual.

O ponto de entrada principal, helloworld.php, essencialmente passa o controle para o controller, que lida com a execução da tarefa que foi especificada na solicitação. Nosso componente controller não faz nada mais do que a classe pai já faz, razão pela qual nossa classe controll está vazia.

controller.php

class HelloWorldController extends JControllerLegacy
{
}

Quando nenhuma tarefa é informada nas variáveis de requisição, a tarefa padrão será executada. É a tarefa de exibição (display) por padrão. A classe JControllerLegacy tem essa tarefa. Em nosso exemplo, ele exibirá uma view chamada HelloWorld.

view.html.php

class HelloWorldViewHelloWorld extends JViewLegacy
{
	function display($tpl = null)
	{
		// Assign data to the view
		$this->msg = 'Hello World';
 
		// Display the view
		parent::display($tpl);
	}
}

A view configura o texto a ser exibido e, em seguida, chama a classe base de visão. JViewLegacy é uma classe base de visão Joomla!. No nosso caso, este método exibirá dados usando o arquivo tmpl/default.php.

Caveat: If your view needs to load or otherwise embed individual JavaScript code, do not do that in the view, as the code might not get included when caching is enabled. Load those scripts in the controller instead. See the related issue on the issue tracker.

default.php

<h1><?php echo $this->msg; ?></h1>

Este arquivo de template será incluído pela classe JViewLegacy. Portanto, aqui, $this refere-se à classe HelloWorldViewHelloWorld.

helloworld.xml

<version>0.0.2</version>

Atualiza o número da versão.

<filename>controller.php</filename>
<folder>views</folder>

Diz aplicação de instalação para incluir controller.php e o diretório de views

Component Contents

At this point in the tutorial, your component should contain the following files:

1 helloworld.xml this is an XML (manifest) file that tells Joomla! how to install our component.
2 site/helloworld.php this is the site entry point to the Hello World! component
3 site/index.html prevents web server from listing directory content
4 site/controller.php file representing the controller
5 site/views/index.html prevents web server from listing directory content
6 site/views/helloworld/index.html prevents web server from listing directory content
7 site/views/helloworld/view.html.php file representing the view
8 site/views/helloworld/tmpl/index.html prevents web server from listing directory content
9 site/views/helloworld/tmpl/default.php the default view
10 admin/index.html prevents web server from listing directory content
11 admin/helloworld.php this is the administrator entry point to the Hello World! component
12 admin/sql/index.html prevents web server from listing directory content
13 admin/sql/updates/index.html prevents web server from listing directory content
14 admin/sql/updates/mysql/index.html prevents web server from listing directory content
15 admin/sql/updates/mysql/0.0.1.sql file allowing to initialise schema version of the com_helloworld component.
Info non-talk.png
General Information

Please create a pull request or issue at https://github.com/joomla/Joomla-3.2-Hello-World-Component for any code descprepancies or if editing any of the source code on this page.