logo
  • Home
  • Acerca
  • Autores
  • Faq
  • Rede
  • Mobile
  Twitter   Feed-me! RSS!
Mar 10

XAMLCast – 2a Temporada – Episódio 9 – Finger Style, SLARToolkit, Windows Phone 7 e pré-MIX10

Escrito por XAML Cast em .NET, 1, 3d, 4, 6, AR, AUG, Artigo, BI, Blend, Blogs, Curso, DRE, Design, Dicas, Evento, Ferramenta, IE, MIX, MSDN, Microsoft, Notícias, Novidades, O, Pessoal, RIA, Revisão, Ria’s Geral, Ria's Geral, Tech, WPF, back, blog, class, codeplex, concurso, embedded, engine, entrevista, err, event, expression, for, framework, html, iTunes, ide, kit, live, mg, multitouch, novidade, on, player, podcast, ps3, realidade aumentada, referencia, rss, silverlight, tag @ 03 10th, 2010 | via http://www.xamlcast.net | Sem comentários
XAML Cast
? X
  • Bookmarks

Blinkbits BlinkLists BlogLines Blogmarks Buddymarks CiteULike Co.mments Del.icio.us Digg Diigo

Fark Feed Me Links Furl Google Linkagogo ma.gnolia Mister Wong Newsvine Propeller Rawsugar

Reddit Rojo Simpy Sphinn Spurl Squidoo StumbleUpon Tailrank Technorati Yahoo

More »

Olá olá pessoal!

Este é o XAMLCast pré-MIX10.

Estamos ansiosos para a chegada deste grande evento que irá nos trazer grandes novidades e anúncios. E para nossa alegria, e como já havíamos falado antes, o XAMLCaster Kelps estará em Las Vegas cobrindo o evento e enviando tudo em primeira mão!

Neste episódio falamos de:

  • Finger Style – Artigo fantástico do Charles Petzold sobre Multitouch em Silverlight

    • http://msdn.microsoft.com/en-us/magazine/ee336026.aspx
  • MultiTouchVista – simulador de multitouch com múltiplos mouses para Windows

    • http://multitouchvista.codeplex.com
  • Artigo do Roberto Sonnino (em inglês) sobre touch com WPF e MultiTouchVista

    • http://www.codeproject.com/KB/WPF/3D-BookWriter.aspx
  • SLARToolkit – A experiência de AR (Realidade Aumentada) com Silverlight virou um framework

    • http://kodierer.blogspot.com/2010/02/slartoolkit-silverlight-augmented.html
  • Aplicação do correio americano para tamanhos de caixas com AR

    • https://www.prioritymail.com/simulator.asp
    • http://www.youtube.com/watch?v=WpS3LeCiCtc&feature=player_embedded
  • Não confunda:

    • Blender – programa de modelagem 3D

      • http://www.blender.org/
    • Balder – engine 2D/3D que funciona com Silverlight

      • http://balder.codeplex.com/
    • Blend – ferramenta para design de aplicações WPF/Silverlight

      • http://www.microsoft.com/expression/products/Blend_Overview.aspx
  • Concurso de Silverlight/WPF da Magenic Studios – prêmios até 500 US$ + 3000 US$ pro Haiti

    • http://magenic.com/Default.aspx?tabid=1835
  • Copa de Talentos Microsoft

    • http://talentosmicrosoft.com.br/
  • Anuncio oficial do Silverlight no Windows Phone 7

    • http://bit.ly/ci8rrI
  • Video no TechEd Middle East mostrando XNA no Windows Phone, Xbox e Windows

    • http://www.youtube.com/watch?v=LQv_3fwopo8
  • MIX10

    • http://live.visitmix.com
  • HVP no MIX

    • http://silverlighthvp.codeplex.com/wikipage?title=ReleaseSchedule
  • Video do ScottGu no Channel 9 falando sobre o MIX

    • http://channel9.msdn.com/posts/LarryLarsen/Countdown-to-MIX10-The-Gu/

Bolão do MIX10!
Envie sua previsão do que irá acontecer no MIX10. Para participar, basta referenciar a hashtag #bolaoxamlcast no seu post do twitter.

Ajudem o XAMLCast a entrevistar o ScottGu no MIX10
Envie um tweet (em inglês) para @ScottGu pedindo uma entrevista com o @XAMLCast (Brazilian Podcast) ou @kelps.

Com muitos pedindo, o acesso torna-se mais fácil.

Se quiserem, podem pedir para outras “personalidades” do .net/WPF/SL, como Scott Hanselman, Phil Haack, John Papa, S. Somasegar, Tim Heuer, Karen Corby, Glenn Block… o Kelps vai ter trabalho em Vegas!

Atenção!

O XAMLCast da semana que vem será especial sobre o MIX10! Assim, em vez de um grande episódio, soltaremos as notícias aos poucos, o mais rápido possível, conforme o Kelps for mandando. Por isso, não deixe de assinar e seguir o XAMLCast para não perder nada!

Para assinar:

  • Feed RSS: http://www.xamlcast.net
  • iTunes/iPod: pcast://www.xamlcast.net
  • Zune: zune://subscribe/?XAMLCast=http://www.xamlcast.net

O XAMLCast também está no Twitter!

- Twitter oficial: @xamlcast (e hashtag #xamlcast)

- Siga os XAMLCasters:

  • @kelps
  • @robertos_br
  • @rodrigokono

- Adicione o Twibbon do XAMLCast ao seu avatar!

  • http://twibbon.com/join/XAMLCast

Até o próximo!

Abraços,

Kelps, Roberto Sonnino e Rodrigo Kono

http://feedproxy.google.com/~r/xamlcast/~5/YyvAWh0-fbY/xamlcast – 2×09.mp3

Mar 9

Iniciando com o Mate Framework

Escrito por Ved em 1, Actionscript3, Download, Flex, Flex Builder, Flex For Kids, Flex For Kids 2010, Gravação, IE, Mate, Mate Flex Framework, O, Orientação a Objetos, Palestra, Ria’s Geral, Screencast, Ved, for, framework, mvc, screen, tv @ 03 9th, 2010 | via http://www.vedovelli.com.br | Sem comentários
Ved
? X
  • Bookmarks

Blinkbits BlinkLists BlogLines Blogmarks Buddymarks CiteULike Co.mments Del.icio.us Digg Diigo

Fark Feed Me Links Furl Google Linkagogo ma.gnolia Mister Wong Newsvine Propeller Rawsugar

Reddit Rojo Simpy Sphinn Spurl Squidoo StumbleUpon Tailrank Technorati Yahoo

More »

Este é o screencast que enviei como extra à gravação da minha palestra no Flex For Kids 2010.

Download: http://blip.tv/file/get/Vedovelli-IniciaoAoMateFramework393.flv

http://blip.tv/file/get/Vedovelli-IniciaoAoMateFramework393.flv

Mar 8

Entrevista com Stefan Horochovec

Escrito por Ved em 1, AR, Adobe, Desenvolvimento, Diversos, Flex, FlexDuck, O, Opinião, Ria’s Geral, Software, Twitter, UI, Ved, blog, código, código fonte, entrevista, flash, fonte, framework, if, mvc, on @ 03 8th, 2010 | via http://www.vedovelli.com.br | Sem comentários
Ved
? X
  • Bookmarks

Blinkbits BlinkLists BlogLines Blogmarks Buddymarks CiteULike Co.mments Del.icio.us Digg Diigo

Fark Feed Me Links Furl Google Linkagogo ma.gnolia Mister Wong Newsvine Propeller Rawsugar

Reddit Rojo Simpy Sphinn Spurl Squidoo StumbleUpon Tailrank Technorati Yahoo

More »

Stefan Horochovec
Engenheiro de Software
Adobe Community Manager – http://www.flexduck.org/
Blog: http://www.horochovec.com.br/
Twitter: http://twitter.com/horochovec
Ved: Em sua opinião, qual a importância de um framework MVC para Flex?
Stefan: A adoção de um framework no desenvolvimento da aplicação contribui bastante com a manutenção do projeto, com a qualidade do código fonte (padronização), e por possuir diversos facilitadores para a codificação, [...]

Mar 4

Modules

Escrito por Fabio da Silva em 1, 2.0, 2009, 4, 6, AR, Actionscript, Adobe, Adobe Flex, Air, Aplicativos, BI, Blogs, Controls, Download, EventListener, Flex, Flex 2, Flex 3, Flex Builder, Google, IE, MXML, Number, O, RIA, RTM, Ria’s Geral, TAT, Tech, UI, XML, action, api, app, blog, class, classe, classes, components, control, developer, dynamic, event, events, finally, flash, for, framework, function, handle, html, ide, if, int, interface, map, mg, on, player, pt, reference, runtime, singleton, swf @ 03 4th, 2010 | via http://fabiophx.blogspot.com | Sem comentários
Fabio da Silva
? X
  • Bookmarks

Blinkbits BlinkLists BlogLines Blogmarks Buddymarks CiteULike Co.mments Del.icio.us Digg Diigo

Fark Feed Me Links Furl Google Linkagogo ma.gnolia Mister Wong Newsvine Propeller Rawsugar

Reddit Rojo Simpy Sphinn Spurl Squidoo StumbleUpon Tailrank Technorati Yahoo

More »

Estou estudando sobre módulos (Flex 3 Developer Guide) e fiz um resumo dos tópicos que achei importantes para melhor fixação e abaixo estou disponibilizando este resumo.

About modules

Modules
are SWF files that can be loaded and unloaded by an application. They cannot be run independently of an application, but any number of applications can share the modules.
The main application, can dynamically load other modules that it requires, when it needs them.


Benefits of modules
  • Smaller initial download size of the SWF file.
  • Shorter load time due to smaller SWF file size.
  • Better encapsulation of related aspects of an application.
A module is a special type of dynamically loadable SWF that contains an IFlexModuleFactory class factory. This allows an application to load code at run time and create class instances without requiring that the class implementations be linked into the main application. Modules are similar to Runtime Shared Libraries (RSLs) in that they separate code from an application into separately loaded SWF files. Modules are much more flexible than RSLs because modules can be loaded and unloaded at run time and compiled without the application.

ModuleManager and ModuleLoader

The ModuleManager manages the set of loaded modules, which are treated as a map of Singletons that are indexed by the module URL. The ModuleLoader class is a thin layer on top of the ModuleManager API that is intended to act similarly to the mx.controls.SWFLoader class for modules that only define a single visual UIComponent. The ModuleLoader class is the easiest class to use when implementing a module-based architecture, but the ModuleManager provides greater control over the modules.

Module domains

By default, a module is loaded into a child domain of the current application domain. You can specify a different application domain by using the applicationDomain property of the ModuleLoader class. Because a module is loaded into a child domain, it owns class definitions that are not in the main application’s domain. For example, the first module to load the PopUpManager class becomes the owner of the PopUpManager class for the entire application because it registers the manager with the SingletonManager. If another module later tries to use the PopUpManager, Adobe ® Flash® Player throws an exception. The solution is to ensure that managers such as PopUpManager and DragManager and any other shared services are defined by the main application (This technique also applies to components). Typically, this is done by adding the following to a script block:


import mx.managers.PopUpManager;

import mx.managers.DragManager;

private var popUpManager:PopUpManager;

private var dragManager:DragManager;

Because a Flex module must be in the same security domain as the application (SWF) that loads it, when you’re using modules in an AIR application any module SWF must be located in the same directory as the main application SWF or one of its subdirectories, which ensures that like the main application SWF, the module SWF is in the AIR application security sandbox.

Creating ActionScript-based modules

If your module does not include any framework code, you can create a class that extends ModuleBase. If you use the ModuleBase class, your module will typically be smaller than if you use a module based on the Module class because it does not have any framework class dependencies.

Reducing module size

Module size varies based on the components and classes that are used in the module. By default, a module includes all framework code that its components depend on, which can cause modules to be large by linking classes that overlap with the application’s classes.

To reduce the size of the modules, you can optimize the module by instructing it to externalize classes that are included by the application. The result is that the module includes only the classes it requires, while the framework code and other dependencies are included in the application.

To externalize framework classes with the command-line compiler, you generate a linker report from the application that loads the modules. You then use this report as input to the module’s load-externs compiler option. The compiler externalizes all classes from the module for which the application contains definitions. This process is also necessary if your modules are in a separate project from your main application in Flex Builder.

1. Generate the linker report and compile the application:
mxmlc -link-report=report.xml MyApplication.mxml

2. Compile the module and pass the linker report to the load-externs option:

mxmlc -load-externs=report.xml MyModule.mxml

Note: If you externalize the module’s dependencies by using the load-externs or optimize option, your module might not be compatible with future versions of Adobe Flex.

Using the ModuleManager class to load modules

To use the ModuleManager to load a module in ActionScript, you first get a reference to the module’s IModuleInfo interface by using the ModuleManager getModule() method. You then call the interface’s load() method.

Finally, you use the factory property of the interface to call the create() method and cast the return value as the module’s class.

import mx.events.ModuleEvent;
import mx.modules.ModuleManager;
import mx.modules.IModuleInfo;
public var info:IModuleInfo;

private function initApp():void {


info = ModuleManager.getModule(“ColumnChartModule.swf”);
info.addEventListener(ModuleEvent.READY, modEventHandler);
// Load the module into memory. Calling load() makes the
// IFlexModuleFactory available. You can then get an
// instance of the class using the factory’s create() method.
info.load();

}

private function modEventHandler(e:ModuleEvent):void {

// Add an instance of the module’s class to the display list.
vb1.addChild(info.factory.create() as ColumnChartModule);

}

See also:
Gerenciamento de memória e tamanho dos arquivos em grandes aplicativos utilizando o Modules do Flex 2.0.1

Mar 4

Evitando problemas com Views e DTOs

Escrito por DClick Team em 1, 4, 6, AR, Access, Apresentação, BI, Componente, Data Binding, Download, Flex, Flex Components, Frameworks, FullScreen, IE, Mac, O, Partilha, Ria’s Geral, Screencast, TAT, Twitter, UI, UX, app, class, código, código fonte, dados, err, exemplo, flash, fonte, framework, gc, if, lógica, on, problema, problemas, pt, screen, string, swf, tv, wave @ 03 4th, 2010 | via http://blog.dclick.com.br/pt/ | Sem comentários
DClick Team
? X
  • Bookmarks

Blinkbits BlinkLists BlogLines Blogmarks Buddymarks CiteULike Co.mments Del.icio.us Digg Diigo

Fark Feed Me Links Furl Google Linkagogo ma.gnolia Mister Wong Newsvine Propeller Rawsugar

Reddit Rojo Simpy Sphinn Spurl Squidoo StumbleUpon Tailrank Technorati Yahoo

More »

Twitter!

No seu aplicativo você tem um DTO cujo os dados são renderizados por diferentes Views (telas). Então, toda hora que o seu DTO muda, você percebe sua aplicação travada por uns segundos. Depois de um tempo você percebe que o problema é que mesmo as telas que estão invisíveis estão executando código de apresentação de dados com base no novo DTO. Bem, este é um problema comum quando trabalhamos com DTOs complexos e abusamos do Data Binding.

A notícia ruim é que se você não teve este problema ainda, um dia você terá. A notícia boa é que uma das maneiras de evitar este problema é utilizar o DTOViewHelper, componente disponibilizado neste screencast.

Alguns Frameworks atuais do Flex oferecem maneiras de resolver este problema, mas o DTOViewHelper é independente do Framework que você usa. Além disso, como pode ser visto no Screencast, você pode definir métodos auxiliares dentro do DTOViewHelper com o objetivo compartilhar lógica de apresentação de dados de DTOs entre diferentes Views (veja o exemplo da Data que mostra a string “Hoje” no Screencast).

Clique aqui para fazer o download do código fonte do exemplo “errado” (I could be WRONG).

Clique aqui para fazer o download do código fonte do exemplo “certo” (I could be RIGHT).

Fev 22

Lumine + ZendAmf + Flex 5/5

Escrito por Fábio Batista da Silva em 1, 4, 6, AMF, AR, Adobe, Adobe Flex, Arquitetura, BI, Bindable, Controls, DataGrid, DataProvider, Desenvolvedor, EventListener, Evento, Eventos, Flex, Flex 2, Flex 3, Flex 4, IE, Iniciando, Java, MXML, Number, O, PHP, Pessoal, Projetos, RIA, Ria’s Geral, TAT, Tema, TextInput, Tutorial, UI, Ved, XML, XP, action, app, auto, back, backend, bar, busca, class, control, código, código fonte, demo, desenvolvedores, dispatch, dispatchEvent, email, err, erro, event, events, fonte, for, framework, function, handle, ide, if, label, layout, on, pt, servidor, tag, tv, update, vs, zend, zendAMF, zendFramework @ 02 22nd, 2010 | via http://www.flexria.com.br/home | Sem comentários
Fábio Batista da Silva
? X
  • Bookmarks

Blinkbits BlinkLists BlogLines Blogmarks Buddymarks CiteULike Co.mments Del.icio.us Digg Diigo

Fark Feed Me Links Furl Google Linkagogo ma.gnolia Mister Wong Newsvine Propeller Rawsugar

Reddit Rojo Simpy Sphinn Spurl Squidoo StumbleUpon Tailrank Technorati Yahoo

More »

Lumine + ZendAmf + Flex 5/5

Olá pessoal !!!

Agora que temos nosso backend e regra de negocio pronta podemos implementar nossas views e actions.

Application

Iniciando pelo nosso application que terá apenas as configurações do Swiz e uma instância de nossa view :

<?xml version="1.0" encoding="utf-8"?>
<mx:Application 
	xmlns:mx="http://www.adobe.com/2006/mxml" 
	xmlns:swiz="http://swiz.swizframework.org"
	xmlns:views="br.com.flexria.views.*"
	layout="absolute" xmlns:local="*"
	creationPolicy="all"
	height="100%"
	width="100%">
 
	<local:ApplicationSwizConfig/>
 
	<views:ContactView 
		horizontalCenter="0" 
		verticalCenter="0"
		width="600"
		bottom="20" 
		top="20"/>
</mx:Application>

Views

A aplicação possui 2 view extremamente simples ContactView e PhoneView, sendo que a segunda será utilizado como filha da primeira:

ContactView.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Panel 
	xmlns:mx="http://www.adobe.com/2006/mxml"
	xmlns:views="br.com.flexria.views.*" 
 	creationComplete="{init()}"
 	title="Contatos">
	<mx:Script source="actions/ContactAction.as"/>
	<mx:ViewStack id="_vs" width="100%" height="100%">
		<mx:Canvas width="100%" height="100%" id="_canvasList">
			<mx:HBox left="20" right="20" top="5">
				<mx:Label text="Nome"/>
				<mx:TextInput id="_txFind" width="80%"/>
				<mx:Button label="Buscar" click="find()"/>
			</mx:HBox>
			<mx:DataGrid 
				id="_dataGrid"
				top="40"
				left="10"
				right="10"
				bottom="60" 
				doubleClick="update()"
				doubleClickEnabled="true"
				dataProvider="{contactController.dataProvider}" >
				<mx:columns>
					<mx:DataGridColumn headerText="Nome" 	dataField="name"/>
					<mx:DataGridColumn headerText="Email" 	dataField="email"/>
				</mx:columns>
			</mx:DataGrid>
			<mx:ControlBar bottom="10" width="95%" horizontalCenter="0" horizontalAlign="left" verticalAlign="middle">
				<mx:Button label="Novo" 	id="_btnCreate" 	click="{create()}"/>
				<mx:Button label="Editar" 	id="_btnUpdate" 	click="{update()}"		enabled="{_dataGrid.selectedItem!=null}"/>
				<mx:Button label="Remover" 	id="_btnRemove" 	click="{remove()}"		enabled="{_dataGrid.selectedItem!=null}"/>
			</mx:ControlBar>
		</mx:Canvas>
		<mx:Canvas  width="100%" height="100%" id="_canvasForm">
			<mx:TabNavigator width="100%" height="100%">
				<mx:Form 
					top="10"
					left="10"
					right="10"
					bottom="10" 
					borderStyle="solid" label="Contato">
					<mx:FormHeading label="{contact.id>0?'Editando':'Incluindo'} contato"/>
					<mx:FormItem label="Nome:" required="true">
						<mx:TextInput 
							width="339" 
							id="_txtName" 
							text="{contact.name}"/>
					</mx:FormItem>
					<mx:FormItem label="Email:">
						<mx:TextInput 
							width="339" 
							id="_txtEmail" 
							text="{contact.email}"/>
					</mx:FormItem>
					<mx:FormItem width="100%" direction="horizontal">
						<mx:Button label="Cancelar" id="_btnCancel" 	click="{cancel()}"/>
						<mx:Button label="Confirmar" id="_btnConfirm" 	click="{save()}"/>
					</mx:FormItem>
				</mx:Form>
                                <!--Instancia de PhoneView-->
				<views:PhoneView 
					id="_phoneView" 
					contact="{contact}" 
					label="Telefones" 
					enabled="{contact.id>0}"/>
			</mx:TabNavigator>
		</mx:Canvas>
	</mx:ViewStack>
</mx:Panel>

PhoneView.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas 
	xmlns:mx="http://www.adobe.com/2006/mxml" 
 	creationComplete="{init()}">
	<mx:Script source="actions/PhoneAction.as"/>
	<mx:ViewStack id="_vs" width="100%" height="100%">
		<mx:Canvas width="100%" height="100%" id="_canvasList">
			<mx:DataGrid 
				id="_dataGrid"
				top="10"
				left="10"
				right="10"
				bottom="60" 
				doubleClick="update()"
				doubleClickEnabled="true"
				dataProvider="{phoneController.dataProvider}" >
				<mx:columns>
					<mx:DataGridColumn headerText="Número" 	dataField="number"/>
				</mx:columns>
			</mx:DataGrid>
			<mx:ControlBar bottom="10" width="95%" horizontalCenter="0" horizontalAlign="left" verticalAlign="middle">
				<mx:Button label="Novo" 	id="_btnCreate" 	click="{create()}"/>
				<mx:Button label="Editar" 	id="_btnUpdate" 	click="{update()}"		enabled="{_dataGrid.selectedItem!=null}"/>
				<mx:Button label="Remover" 	id="_btnRemove" 	click="{remove()}"		enabled="{_dataGrid.selectedItem!=null}"/>
			</mx:ControlBar>
		</mx:Canvas>
		<mx:Canvas  width="100%" height="100%" id="_canvasForm">
			<mx:Form 
				top="10"
				left="10"
				right="10"
				bottom="10" 
				borderStyle="solid">
				<mx:FormHeading label="{phone.id>0?'Editando':'Incluindo'} telefone"/>
				<mx:FormItem label="Número:" required="true">
					<mx:TextInput 
						width="339" 
						id="_txtNumber" 
						text="{phone.number}"/>
				</mx:FormItem>
				<mx:FormItem width="100%" direction="horizontal">
					<mx:Button label="Cancelar" id="_btnCancel" 	click="{cancel()}"/>
					<mx:Button label="Confirmar" id="_btnConfirm" 	click="{save()}"/>
				</mx:FormItem>
			</mx:Form>
		</mx:Canvas>
	</mx:ViewStack>
</mx:Canvas>

Actions

E para finalizar as respectivas Actions para ContactView e PhoneView.
Essas action possuem os métodos que disparam os eventos de chamada ao servidor e métodos handler que serão chamados quando a requisição for completada.
Além disso temos a meta tag [Autowire] que faz a injeção do respectivo controller.
ContactAction.as

import br.com.flexria.controllers.ContactController;
import br.com.flexria.events.ContactEvent;
import br.com.flexria.vo.ContactVO;
import org.swizframework.Swiz;
import mx.events.CloseEvent;
import mx.controls.Alert;
 
 
[Bindable]
private var contact:ContactVO=new ContactVO();
 
[Bindable]
[Autowire]
public var contactController:ContactController;
 
/**
 * init()
 */
private function init():void
{
	find();
 
	Swiz.addEventListener(ContactEvent.SAVE_COMPLETE, saveCompleteHandler);
	Swiz.addEventListener(ContactEvent.REMOVE_COMPLETE, removeCompleteHandler);
}
 
/**
 * create()
 */
private function create():void
{
	contact=new ContactVO();
	_vs.selectedChild=_canvasForm;
}
 
/**
 * update()
 */
private function update():void
{
	contact=_dataGrid.selectedItem as ContactVO;
	_vs.selectedChild=_canvasForm;
}
 
/**
 * cancel()
 */
private function cancel():void
{
	contact=new ContactVO();
	_vs.selectedChild=_canvasList;
}
 
/**
 * find()
 */
private function find():void
{
	_vs.selectedChild=_canvasList;
	var event:ContactEvent=new ContactEvent(ContactEvent.FIND);
	event.contact=new ContactVO();
	event.contact.name=_txFind.text;
	Swiz.dispatchEvent(event);
}
 
/**
 * save()
 */
private function save():void
{
	contact.name=_txtName.text;
	contact.email=_txtEmail.text;
	var event:ContactEvent=new ContactEvent(ContactEvent.SAVE);
	event.contact=contact;
	Swiz.dispatchEvent(event);
}
 
/**
 * remove()
 */
private function remove():void
{
	Alert.show("Deseja realmente excluir o registro selecionado?", "Excluir", Alert.NO | Alert.YES | Alert.NONMODAL, null, function(e:CloseEvent):void
	{
		if (e.detail == Alert.YES)
		{
			contact=_dataGrid.selectedItem as ContactVO;
			var event:ContactEvent=new ContactEvent(ContactEvent.REMOVE);
			event.contact=contact;
			Swiz.dispatchEvent(event);
		}
	});
 
}
 
/**
 * saveCompleteHandler()
 */
private function saveCompleteHandler(event:Event):void
{
	_vs.selectedChild=_canvasList;
	find();
}
 
/**
 * removeCompleteHandler()
 */
private function removeCompleteHandler(event:Event):void
{
	_vs.selectedChild=_canvasList;
	find();
}

PhoneAction.as

import br.com.flexria.controllers.ContactController;
import br.com.flexria.controllers.PhoneController;
import br.com.flexria.events.ContactEvent;
import br.com.flexria.events.PhoneEvent;
import br.com.flexria.vo.ContactVO;
import br.com.flexria.vo.PhoneVO;
import org.swizframework.Swiz;
import mx.events.CloseEvent;
import mx.controls.Alert;
 
[Bindable]
private var _contact:ContactVO;
 
[Bindable]
private var phone:PhoneVO=new PhoneVO();
 
[Bindable]
[Autowire]
public var phoneController:PhoneController;
 
public function set contact(value:ContactVO):void
{
	_contact=value;
	if (_contact != null && _contact.id > 0)
	{
		load();
	}
}
 
/**
 * init()
 */
private function init():void
{
	Swiz.addEventListener(PhoneEvent.SAVE_COMPLETE, saveCompleteHandler);
	Swiz.addEventListener(PhoneEvent.REMOVE_COMPLETE, removeCompleteHandler);
}
 
/**
 * load()
 */
private function load():void
{
	_vs.selectedChild=_canvasList;
	var event:PhoneEvent=new PhoneEvent(PhoneEvent.LOAD);
	event.contact=_contact;
	Swiz.dispatchEvent(event);
}
 
/**
 * create()
 */
private function create():void
{
	phone=new PhoneVO();
	_vs.selectedChild=_canvasForm;
}
 
/**
 * update()
 */
private function update():void
{
	phone=_dataGrid.selectedItem as PhoneVO;
	_vs.selectedChild=_canvasForm;
}
 
/**
 * cancel()
 */
private function cancel():void
{
	phone=new PhoneVO();
	_vs.selectedChild=_canvasList;
}
 
/**
 * save()
 */
private function save():void
{
	phone.contactId=_contact.id;
	phone.number=_txtNumber.text;
	var event:PhoneEvent=new PhoneEvent(PhoneEvent.SAVE);
	event.phone=phone;
	Swiz.dispatchEvent(event);
}
 
/**
 * remove()
 */
private function remove():void
{
	Alert.show("Deseja realmente excluir o registro selecionado?", "Excluir", Alert.NO | Alert.YES | Alert.NONMODAL, null, function(e:CloseEvent):void
	{
		if (e.detail == Alert.YES)
		{
			phone=_dataGrid.selectedItem as PhoneVO;
			var event:PhoneEvent=new PhoneEvent(PhoneEvent.REMOVE);
			event.phone=phone;
			Swiz.dispatchEvent(event);
		}
	});
 
}
 
/**
 * saveCompleteHandler()
 */
private function saveCompleteHandler(event:Event):void
{
	_vs.selectedChild=_canvasList;
	load();
}
 
/**
 * removeCompleteHandler()
 */
private function removeCompleteHandler(event:Event):void
{
	_vs.selectedChild=_canvasList;
	load();
}

Assim finalizamos nossa aplicação !!!

O código fonte da aplicação pode ser baixado aqui

Espero que esse tutorial possa ser utíl aos desenvolvedores PHP que pretendem utilizar essa arquitetura em seus projetos e peço desculpas por algum erro ou se deixei de explicar algo durante o post.
Se houver alguma duvida podem podem perguntar via comentário no post ou email Q respondo na medida do possível..

Abraço a todos e até a próxima !!!!

Tutorial : Lumine + ZendAmf + Flex 1/5
Tutorial : Lumine + ZendAmf + Flex 2/5
Tutorial : Lumine + ZendAmf + Flex 3/5
Tutorial : Lumine + ZendAmf + Flex 4/5
Tutorial : Lumine + ZendAmf + Flex 5/5

Fev 22

Lumine + ZendAmf + Flex 4/5

Escrito por Fábio Batista da Silva em 1, 4, 6, AMF, AR, Adobe Flex, BI, Bindable, Controls, DataProvider, Dica, Evento, Eventos, Flex, Flex 2, Flex 3, Flex 4, IE, Java, MXML, Number, O, PHP, Pessoal, RIA, Remoting, Ria’s Geral, RoR, Sun, TAT, Tutorial, UI, XML, action, auto, boolean, class, classe, classes, collection, control, demo, dispatch, dispatchEvent, email, err, erro, error, event, events, flash, for, framework, function, handle, ide, if, int, lista, map, on, override, servidor, string, tag, tv, uint, zend, zendAMF, zendFramework @ 02 22nd, 2010 | via http://www.flexria.com.br/home | Sem comentários
Fábio Batista da Silva
? X
  • Bookmarks

Blinkbits BlinkLists BlogLines Blogmarks Buddymarks CiteULike Co.mments Del.icio.us Digg Diigo

Fark Feed Me Links Furl Google Linkagogo ma.gnolia Mister Wong Newsvine Propeller Rawsugar

Reddit Rojo Simpy Sphinn Spurl Squidoo StumbleUpon Tailrank Technorati Yahoo

More »

Lumine + ZendAmf + Flex 4/5

Olá pessoal !!!

Vamos dar continuidade a nossa serie de posts.
no ultimo posto configuramos da nossa aplicação flex, e agora iremos implementar nossas classes de modelo e regra de negocio.

VOs

Começamos criando nossos os VO’s/DTO’s, copias das classes que temos no PHP.
Possuem apenas seus atributos e as meta tag [Bindable] [RemoteClass(alias="xxx")]
Quem Tornam o objeto bindable e mapeiam a classe equivalente no PHP respectivamente.
br.com.flexria.vo.ContactVO e br.com.flexria.vo.PhoneVO

package br.com.flexria.vo
{
	/**
	 * @author Fabio B. Silva
	 */
	[Bindable]
	[RemoteClass(alias="ContactVO")]
	public class ContactVO
	{
		public var id:uint;
		public var name:String;
		public var email:String;
		public var phoneCollection:Array;
 
	}
}
 
package br.com.flexria.vo
{
	/**
	 * @author Fabio B. Silva
	 */
	[Bindable]
	[RemoteClass(alias="PhoneVO")]
	public class PhoneVO
	{
		public var id:uint;
		public var number:String;
		public var contactId:uint;
 
	}
}

Events

E agora os eventos de nossa aplicação que serão utilizados pelo Swiz.
Cada evento possui 6 constantes estáticas que identificarão o evento de chamada ao servidor e o evento de resposta.
br.com.flexria.events.ContactEvent e br.com.flexria.events.PhoneEvent

package br.com.flexria.events
{
	import br.com.flexria.vo.ContactVO;
	import flash.events.Event;
 
	/**
	 * @author Fabio B. Silva
	 */
	public class ContactEvent extends Event
	{
		public static const FIND		:String='ContactEvent.FIND';
		public static const SAVE		:String='ContactEvent.SAVE';
		public static const REMOVE		:String='ContactEvent.REMOVE';
		public static const FIND_COMPLETE	:String='ContactEvent.FIND_COMPLETE';
		public static const SAVE_COMPLETE	:String='ContactEvent.SAVE_COMPLETE';
		public static const REMOVE_COMPLETE	:String='ContactEvent.REMOVE_COMPLETE';
 
 
		public var contact:ContactVO;
 
		public function ContactEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
		{
			super(type, bubbles, cancelable);
		}
 
		public override function clone():Event
		{
			return new ContactEvent(type, bubbles, cancelable);
		}
 
	}
}
 
package br.com.flexria.events
{
	import br.com.flexria.vo.ContactVO;
	import br.com.flexria.vo.PhoneVO;
	import flash.events.Event;
 
	/**
	 * @author Fabio B. Silva
	 */
	public class PhoneEvent extends Event
	{
		public static const LOAD		:String='PhoneEvent.LOAD';
		public static const SAVE		:String='PhoneEvent.SAVE';
		public static const REMOVE		:String='PhoneEvent.REMOVE';
		public static const LOAD_COMPLETE	:String='PhoneEvent.LOAD_COMPLETE';
		public static const SAVE_COMPLETE	:String='PhoneEvent.SAVE_COMPLETE';
		public static const REMOVE_COMPLETE	:String='PhoneEvent.REMOVE_COMPLETE';
 
 
		public var phone:PhoneVO;
		public var contact:ContactVO;
 
		public function PhoneEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
		{
			super(type, bubbles, cancelable);
		}
 
		public override function clone():Event
		{
			return new PhoneEvent(type, bubbles, cancelable);
		}
 
	}
}

Delegates

Vamos então aos delegates que farão as chamadas as métodos remotos do PHP.
Apenas três métodos em cada um deles, para salvar/remover/listar.
Além disso temos a meta tag [Autowire(bean="xxx")] que indica ao Swiz que ali deve ser injetado o bean “xxx” mapeado no BeanLoader.

br.com.flexria.delegates.ContactDelegate e br.com.flexria.delegates.PhoneDelegate

package br.com.flexria.delegates
{
	import mx.rpc.remoting.mxml.RemoteObject;
	import br.com.flexria.vo.ContactVO;
	import mx.rpc.AsyncToken;
 
	/**
	 * @author Fabio B. Silva
	 */
	public class ContactDelegate
	{
		[Autowire(bean="contactRemote")]
		public var contactRemote:RemoteObject;
 
		/**
		 * find()
		 *
		 * @param 	contact:ContactVO
		 * @return 	AsyncToken
		 */
		public function find(contact:ContactVO):AsyncToken
		{
			return contactRemote.find(contact);
		}
 
		/**
		 * save()
		 *
		 * @param 	contact:ContactVO
		 * @return 	AsyncToken
		 */
		public function save(contact:ContactVO):AsyncToken
		{
			return contactRemote.save(contact);
		}
 
		/**
		 * remove()
		 *
		 * @param 	contact:ContactVO
		 * @return 	AsyncToken
		 */
		public function remove(contact:ContactVO):AsyncToken
		{
			return contactRemote.remove(contact);
		}
 
	}
}
 
 
package br.com.flexria.delegates
{
	import mx.rpc.remoting.mxml.RemoteObject;
	import br.com.flexria.vo.ContactVO;
	import br.com.flexria.vo.PhoneVO;
	import mx.rpc.AsyncToken;
 
	/**
	 * @author Fabio B. Silva
	 */
	public class PhoneDelegate
	{
		[Autowire(bean="phoneRemote")]
		public var phoneRemote:RemoteObject;
 
		/**
		 * load()
		 *
		 * @param 	contact:ContactVO
		 * @return 	AsyncToken
		 */
		public function load(contact:ContactVO):AsyncToken
		{
			return phoneRemote.load(contact);
		}
 
		/**
		 * save()
		 *
		 * @param 	phone:PhoneVO
		 * @return 	AsyncToken
		 */
		public function save(phone:PhoneVO):AsyncToken
		{
			return phoneRemote.save(phone);
		}
 
		/**
		 * remove()
		 *
		 * @param 	phone:PhoneVO
		 * @return 	AsyncToken
		 */
		public function remove(phone:PhoneVO):AsyncToken
		{
			return phoneRemote.remove(phone);
		}
 
	}
}

Controllers

Agora podemos implementar nosso controladores.
Eles estendem a classe org.swizframework.controller.AbstractController
e possuem 3 métodos publicos para salvar, remover e listar.
Esses métodos são mapeados pelo Swiz atraves da meta tag [Mediate(event='xxx')] que indica ao Swiz que sempre que o evento ‘xxx’ for disparado esse método deve ser chamado

package br.com.flexria.controllers
{
	import org.swizframework.controller.AbstractController;
	import br.com.flexria.delegates.ContactDelegate;
	import br.com.flexria.events.ContactEvent;
	import mx.collections.ArrayCollection;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.events.FaultEvent;
	import org.swizframework.Swiz;
	import mx.controls.Alert;
 
 
	/**
	 * @author Fabio B. Silva
	 */
	[Bindable]
	public class ContactController extends AbstractController
	{
		[Autowire]
		public var contactDelegate:ContactDelegate;
 
		public var dataProvider:ArrayCollection;
 
 
		/**
		 * find()
		 *
		 * @param 	e:ContactEvent
		 */
		[Mediate(event='ContactEvent.FIND')]
		public function find(e:ContactEvent):void
		{
			executeServiceCall(contactDelegate.find(e.contact), findHandler, faultHandler);
		}
 
		/**
		 * save()
		 *
		 * @param 	e:ContactEvent
		 */
		[Mediate(event='ContactEvent.SAVE')]
		public function salve(e:ContactEvent):void
		{
			executeServiceCall(contactDelegate.save(e.contact), saveHandler, faultHandler);
		}
 
		/**
		 * remove()
		 *
		 * @param 	e:ContactEvent
		 */
		[Mediate(event='ContactEvent.REMOVE')]
		public function remove(e:ContactEvent):void
		{
			executeServiceCall(contactDelegate.remove(e.contact), removeHandler, faultHandler);
		}
 
		/**
		 * findHandler()
		 *
		 * @param 	e:ResultEvent
		 */
		private function findHandler(e:ResultEvent):void
		{
			dataProvider=new ArrayCollection(e.result as Array);
			Swiz.dispatchEvent(new ContactEvent(ContactEvent.FIND_COMPLETE));
		}
 
		/**
		 * saveHandler()
		 *
		 * @param 	e:ResultEvent
		 */
		private function saveHandler(e:ResultEvent):void
		{
			Swiz.dispatchEvent(new ContactEvent(ContactEvent.SAVE_COMPLETE));
		}
 
		/**
		 * removeHandler()
		 *
		 * @param 	e:ResultEvent
		 */
		private function removeHandler(e:ResultEvent):void
		{
			Swiz.dispatchEvent(new ContactEvent(ContactEvent.REMOVE_COMPLETE));
		}
 
		/**
		 * faultHandler()
		 *
		 * @param 	e:FaultEvent
		 */
		private function faultHandler(e:FaultEvent):void
		{
			Alert.show(e.fault.message, "ERROR");
		}
 
	}
}
 
 
package br.com.flexria.controllers
{
	import org.swizframework.controller.AbstractController;
	import br.com.flexria.delegates.PhoneDelegate;
	import br.com.flexria.events.PhoneEvent;
	import mx.collections.ArrayCollection;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.events.FaultEvent;
	import org.swizframework.Swiz;
	import mx.controls.Alert;
 
 
	/**
	 * @author Fabio B. Silva
	 */
	[Bindable]
	public class PhoneController extends AbstractController
	{
		[Autowire]
		public var phoneDelegate:PhoneDelegate;
 
		public var dataProvider:ArrayCollection;
 
 
		/**
		 * find()
		 *
		 * @param 	e:PhoneEvent
		 */
		[Mediate(event='PhoneEvent.LOAD')]
		public function find(e:PhoneEvent):void
		{
			executeServiceCall(phoneDelegate.load(e.contact), loadHandler, faultHandler);
		}
 
		/**
		 * save()
		 *
		 * @param 	e:PhoneEvent
		 */
		[Mediate(event='PhoneEvent.SAVE')]
		public function salve(e:PhoneEvent):void
		{
			executeServiceCall(phoneDelegate.save(e.phone), saveHandler, faultHandler);
		}
 
		/**
		 * remove()
		 *
		 * @param 	e:PhoneEvent
		 */
		[Mediate(event='PhoneEvent.REMOVE')]
		public function remove(e:PhoneEvent):void
		{
			executeServiceCall(phoneDelegate.remove(e.phone), removeHandler, faultHandler);
		}
 
 
 
 
		/**
		 * findHandler()
		 *
		 * @param 	e:ResultEvent
		 */
		public function loadHandler(e:ResultEvent):void
		{
			dataProvider=new ArrayCollection(e.result as Array);
			Swiz.dispatchEvent(new PhoneEvent(PhoneEvent.LOAD_COMPLETE));
		}
 
		/**
		 * saveHandler()
		 *
		 * @param 	e:ResultEvent
		 */
		public function saveHandler(e:ResultEvent):void
		{
			Swiz.dispatchEvent(new PhoneEvent(PhoneEvent.SAVE_COMPLETE));
		}
 
		/**
		 * removeHandler()
		 *
		 * @param 	e:ResultEvent
		 */
		public function removeHandler(e:ResultEvent):void
		{
			Swiz.dispatchEvent(new PhoneEvent(PhoneEvent.REMOVE_COMPLETE));
		}
 
		/**
		 * faultHandler()
		 *
		 * @param 	e:FaultEvent
		 */
		public function faultHandler(e:FaultEvent):void
		{
			Alert.show(e.fault.message, "ERROR");
		}
 
	}
}

Com nossa regra de negocio pronta podemos implementar nossas views e actions.
que é o assunto do próximo post : Tutorial : Lumine + ZendAmf + Flex 5/5

Até já !!!

Tutorial : Lumine + ZendAmf + Flex 1/5
Tutorial : Lumine + ZendAmf + Flex 2/5
Tutorial : Lumine + ZendAmf + Flex 3/5
Tutorial : Lumine + ZendAmf + Flex 4/5
Tutorial : Lumine + ZendAmf + Flex 5/5

Fev 22

Lumine + ZendAmf + Flex 3/5

Escrito por Fábio Batista da Silva em 1, 4, 6, AMF, AR, Adobe, Adobe Flex, Debug, Flex, Flex 2, Flex 3, Flex 4, IE, MXML, Messaging, O, PHP, Pessoal, Projetos, RIA, Remoting, Ria’s Geral, Swiz Framework, Tutorial, UI, XML, app, as3, auto, back, backend, bug, class, control, demo, event, events, for, framework, frontend, if, image, int, map, mg, on, pt, uint, zend, zendAMF, zendFramework @ 02 22nd, 2010 | via http://www.flexria.com.br/home | Sem comentários
Fábio Batista da Silva
? X
  • Bookmarks

Blinkbits BlinkLists BlogLines Blogmarks Buddymarks CiteULike Co.mments Del.icio.us Digg Diigo

Fark Feed Me Links Furl Google Linkagogo ma.gnolia Mister Wong Newsvine Propeller Rawsugar

Reddit Rojo Simpy Sphinn Spurl Squidoo StumbleUpon Tailrank Technorati Yahoo

More »

Lumine + ZendAmf + Flex 3/5

Olá pessoal !!!

Vamos dar continuidade aos posts anteriores que trataram do Backend da nossa aplicação.
Nesse post vamos codificar o frontend da nossa aplicação, para isso vamos utilizar a dubla que se tornou titular em meus projetos : Flex + Swiz framework.

Flex Project

A estrutura do nosso Flex Project fica da seguinte forma :

Estrutura do projeto flex

Estrutura do projeto flex

Flex Compiler

Como estamos usando Swiz e as configurações de remote através do services.xml precisamos adicionar alguns argumento ao Flex Compiler, nesse caso ficou assim : -locale en_US -services=..services.xml -keep-as3-metadata+=Autowire.

RemotingService

Agora podemos configurar nosso RemotingService com o arquivo services.xml
Lembrando que o endpoint uri deve ser alterado para apontar para o seu projeto php
services.xml

<?xml version="1.0" encoding="UTF-8"?>
<services-config>
    <services>
        <service id="zend-service"
            class="flex.messaging.services.RemotingService"
            messageTypes="flex.messaging.messages.RemotingMessage">
            <destination id="zend">
                <channels>
                    <channel ref="zend-endpoint"/>
                </channels>
                <properties>
                    <source>*</source>
                </properties>
            </destination>
        </service>
    </services>
    <channels>
        <channel-definition id="zend-endpoint"
            class="mx.messaging.channels.AMFChannel">
            <endpoint uri="http://localhost/lumine-zend-flex/php/gateway.php"
                class="flex.messaging.endpoints.AMFEndpoint"/>
        </channel-definition>
    </channels>
</services-config>

Swiz

Então podemos configurar o Swiz para isso temos 2 arquivos :
ApplicationSwizConfig.mxml : Responsável pelas configurações básicas do Swiz
ApplicationBeans.mxml : Responsável pelo mapeamento dos nossos beans

ApplicationSwizConfig.mxml

<?xml version="1.0" encoding="utf-8"?>
<swizframework:SwizConfig
	xmlns:mx="http://www.adobe.com/2006/mxml" 
	xmlns:swizframework="org.swizframework.*"
	eventPackages="{['br.com.flexria.events']}"
	viewPackages="{['br.com.flexria.view']}"
	logEventLevel="{LogEventLevel.DEBUG}"
	beanLoaders="{[ApplicationBeans]}"
	injectionEvent="preinitialize"
	mediateBubbledEvents="true"
	strict="true">
 
	<mx:Script>
		<![CDATA[
			import mx.logging.LogEventLevel;
		]]>
	</mx:Script>
 
	<mx:TraceTarget id="logTarget"
		includeCategory="true"
	    includeLevel="true" 
	    includeDate="true" 
	    includeTime="true"/>
 
</swizframework:SwizConfig>

ApplicationBeans.mxml

<?xml version="1.0" encoding="utf-8"?>
<BeanLoader xmlns="org.swizframework.util.*"
		xmlns:mx="http://www.adobe.com/2006/mxml"
		xmlns:factory="org.swizframework.factory.*"
		xmlns:delegates="br.com.flexria.delegates.*"
		xmlns:controllers="br.com.flexria.controllers.*">
 
   <!--DELEGATES-->
   <delegates:ContactDelegate 	id="contactDelegate"/>
   <delegates:PhoneDelegate 	id="phoneDelegate"/>
 
   <!--CONTROLLERS-->
   <controllers:ContactController   id="contactController"/>
   <controllers:PhoneController   id="phoneController"/>
 
   <!--REMOTES-->
   <mx:RemoteObject destination="zend"   id="contactRemote" source="ContactService" />
   <mx:RemoteObject destination="zend"   id="phoneRemote"   source="PhoneService" />
 
</BeanLoader>

Agora que temos nosso projeto flex configurado e podemos começar a codificar p valer : Tutorial : Lumine + ZendAmf + Flex 4/5

Até já !!!

Tutorial : Lumine + ZendAmf + Flex 1/5
Tutorial : Lumine + ZendAmf + Flex 2/5
Tutorial : Lumine + ZendAmf + Flex 3/5
Tutorial : Lumine + ZendAmf + Flex 4/5
Tutorial : Lumine + ZendAmf + Flex 5/5

Fev 22

Lumine + ZendAmf + Flex 2/5

Escrito por Fábio Batista da Silva em 1, 4, 6, AMF, AR, Adobe Flex, Desenvolvimento, Flex, Flex 2, Flex 3, Flex 4, IE, Number, O, Outros, PHP, Pessoal, Projetos, RIA, Ria’s Geral, Tutorial, UI, XP, arte, auto, back, backend, camp, class, classe, classes, collection, código, dados, demo, email, for, framework, function, html, int, lista, on, padrão, rest, serviço, tv, update, zend, zendAMF, zendFramework @ 02 22nd, 2010 | via http://www.flexria.com.br/home | Sem comentários
Fábio Batista da Silva
? X
  • Bookmarks

Blinkbits BlinkLists BlogLines Blogmarks Buddymarks CiteULike Co.mments Del.icio.us Digg Diigo

Fark Feed Me Links Furl Google Linkagogo ma.gnolia Mister Wong Newsvine Propeller Rawsugar

Reddit Rojo Simpy Sphinn Spurl Squidoo StumbleUpon Tailrank Technorati Yahoo

More »

Lumine + ZendAmf + Flex 2/5

Olá pessoal !!!

No post anterior configuramos nosso projeto php com Lumine e ZendAmf.
Essa parte que veremos agora se refere as nossas classes de “modelo” : VO’s e ActiveRecord’s.
Pode parecer meio confuso ou “Muito código” porem tudo isso pode ser gerado no Lumine de maneira bem pratica e rápida através do Lumine reverse.

Entaum vamos lá !!!

ActiveRecord

O Lumine é um ORM Brasileiro para php que utiliza ActiveRecord.
Eu particularmente não gosto muito do padrão ActiveRecord nem do Lumine
porem outros ORM para php como Doctrine e Zend_Db não possuem integração com VO’s/DTO’s.
Então acabei adotando ele como padrão para meus projetos flex + php devido a agilidade no desenvolvimento.

as classes de ActiveRecord estendem o Lumine_Base e possuem o método _initialize que configura os campos da tabela e seus relacionamentos.
Temos então duas classes Contact e Phone.

models/entities/Contact.php e models/entities/Phone.php

class Contact extends Lumine_Base {
 
    protected $_tablename = 'contact';
    protected $_package   = 'models.entities';
 
    public $id;
    public $name;
    public $email;
 
    public $phoneCollection = array();
 
    /**
     * Inicia os valores da classe
     * @return void
     */
    protected function _initialize() {
 
        $this->_addField("id",      "id",       "int",      10,     array('primary' => true, 'notnull' => true, 'autoincrement' => true));
        $this->_addField("name",    "name",     "varchar",  200,    array('notnull' => true));
        $this->_addField("email",   "email",    "varchar",  200,    array());
 
        $this->_addForeignRelation("phoneCollection", self::ONE_TO_MANY, "Phone", "contactId", null, null, null);
    }
}
 
 
class Phone extends Lumine_Base {
 
    protected $_tablename = 'phone';
    protected $_package   = 'models.entities';
 
    public $id;
    public $number;
    public $contactId;
 
    /**
     * Inicia os valores da classe
     * @return void
     */
    protected function _initialize() {
        $this->_addField("id",      "id",       "int",      10,     array('primary' => true, 'notnull' => true, 'autoincrement' => true));
        $this->_addField("number",  "number",   "varchar",  45,     array());
 
        $this->_addField("contactId","contactId",  "int", 10, array(
                'notnull' => true,
                'foreign' => '1',
                'onUpdate' => 'RESTRICT',
                'onDelete' => 'RESTRICT',
                'linkOn' => 'id',
                'class' => 'Contact')
        );
    }
}

VO

Temos também os seus respectivos VO’s/DTO’s para o transporte do dados entre o php e o flex:models/vo/ContactVO.php e models/vo/PhoneVO.php

class ContactVO {
 
    public $id;
    public $name;
    public $email;
    public $phoneCollection = array();
 
    public $_explicitType = 'ContactVO';
}
 
class PhoneVO {
 
    public $id;
    public $number;
    public $contactId;
 
    public $_explicitType = 'PhoneVO';
}

Services

E finalmente nossas classes de serviço apenas três métodos para: salvar, remover e listar:
services/ContactService.php e services/PhoneService.php

class ContactService {
 
    /**
     * @var Contact
     */
    private $contact;
 
    /**
     * construct
     */
    public function __construct() {
        $this->contact = new Contact();
    }
 
    /**
     * getContact()
     *
     * @return Contact
     */
    public function getContact() {
        return $this->contact;
    }
 
    /**
     * findAll()
     *
     * @param   ContactVO $contact
     * @return  array<ContactVO>
     */
    public function find(ContactVO $contact) {
        $this->getContact()->find();
        return $this->getContact()->allToObject();
    }
 
    /**
     * save()
     *
     * @param  ContactVO $contact
     * @return ContactVO $contact
     */
    public function save(ContactVO $contact) {
        $this->getContact()->setFrom($contact);
        $this->getContact()->save();
        return $this->getContact()->toObject();
    }
 
    /**
     * remove()
     *
     * @param  ContactVO $contact
     * @return ContactVO $contact
     */
     public function remove(ContactVO $contact) {
        $phone = new Phone();
        $phone->where("contactId = '{$contact->id}'");
        $phone->delete(true);
 
        $this->getContact()->setFrom($contact);
        $this->getContact()->delete();
        return $this->getContact()->toObject();
    }
}
 
 
 
class PhoneService {
 
    /**
     * @var Phone
     */
    private $phone;
 
    /**
     * construct
     */
    public function __construct() {
        $this->phone = new Phone();
    }
 
    /**
     * getPhone()
     *
     * @return Phone
     */
    public function getPhone() {
        return $this->phone;
    }
 
    /**
     * load()
     *
     * @param   ContactVO $contact
     * @return  array<PhoneVO>
     */
    public function load(ContactVO $contact) {
        $this->getPhone()->where("contactId = '{$contact->id}'");
        $this->getPhone()->find();
        return $this->getPhone()->allToObject();
    }
 
    /**
     * save()
     *
     * @param  PhoneVO $phone
     * @return PhoneVO $phone
     */
    public function save(PhoneVO $phone) {
        $this->getPhone()->setFrom($phone);
        $this->getPhone()->save();
        return $this->getPhone()->toObject();
    }
 
    /**
     * remove()
     *
     * @param  PhoneVO $phone
     * @return PhoneVO $phone
     */
    public function remove(PhoneVO $phone) {
        $this->getPhone()->setFrom($phone);
        $this->getPhone()->delete();
        return $this->getPhone()->toObject();
    }
 
}

Com isso finalizamos tudo que precisamos em nosso Backend
e podemos partir para a aplicação flex : Tutorial : Lumine + ZendAmf + Flex 3/5

Até já !!!

Tutorial : Lumine + ZendAmf + Flex 1/5
Tutorial : Lumine + ZendAmf + Flex 2/5
Tutorial : Lumine + ZendAmf + Flex 3/5
Tutorial : Lumine + ZendAmf + Flex 4/5
Tutorial : Lumine + ZendAmf + Flex 5/5

Fev 22

Lumine + ZendAmf + Flex 1/5

Escrito por Fábio Batista da Silva em 1, 4, 6, AMF, AR, Adobe Flex, BI, Dica, Download, Flex, Flex 2, Flex 3, Flex 4, IE, Links, Number, O, PHP, Password, Pessoal, Projetos, RIA, Ria’s Geral, RoR, Tecnologia, Tutorial, UI, abas, app, auto, back, backend, class, classe, classes, configuração, código, dados, demo, email, engine, err, erro, error, for, framework, function, game, handle, image, int, library, mg, mysql, on, pt, reference, server, uint, zend, zendAMF, zendFramework @ 02 22nd, 2010 | via http://www.flexria.com.br/home | Sem comentários
Fábio Batista da Silva
? X
  • Bookmarks

Blinkbits BlinkLists BlogLines Blogmarks Buddymarks CiteULike Co.mments Del.icio.us Digg Diigo

Fark Feed Me Links Furl Google Linkagogo ma.gnolia Mister Wong Newsvine Propeller Rawsugar

Reddit Rojo Simpy Sphinn Spurl Squidoo StumbleUpon Tailrank Technorati Yahoo

More »

Lumine + ZendAmf + Flex 1/5

Olá pessoal !!!

Peço desculpas para os iniciantes mas este tutorial vai ser p pessoal + avançado, Então temos como requisito para esse tutorial que o leitor tenha um conhecimento básico de Lumine, ZendAmf e Flex.
Vou tentar focar na integração e não nas tecnologias utilizadas. Então vai ser bastante código e pouca teoria.

Parar o Backend vamos utilizar um trio que p mim tem se mostrado bastante produtivo nos últimos projetos e que pode ser baixada nos seguintes links: MYSQL + Lumine + ZendAmf

Base de Dados

Nossa base de dados será bem simples apenas 2 tabelas com um relacionamento 1 X N:

CREATE  DATABASE `lumine_zend_flex`;
 
CREATE TABLE  `contact` (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` varchar(200) NOT NULL,
  `email` varchar(200) DEFAULT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB;
 
CREATE TABLE  `phone` (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `number` varchar(45) NOT NULL,
  `contactId` int(10) UNSIGNED NOT NULL,
  PRIMARY KEY  (`id`),
  KEY `fk_phone_contact` (`contactId`),
  CONSTRAINT `fk_phone_contact` FOREIGN KEY (`contactId`) REFERENCES `contact` (`id`)
) ENGINE=InnoDB;

PHP Project

Bom, depois das libs baixadas e da base instalada vamos configurar nosso projeto php.
A estrutura fica da seguinte forma :

Estrutura do projeto php

Estrutura do projeto php

Arquivos de configuração

Temos 2 arquivos de configuração em nosso projeto
gateway.php : gateway para chamadas amf
lumine-conf.php : Arquivo de configuração do Lumine

gateway.php

//adiciona diretorios ao include path
set_include_path('.'
        . PATH_SEPARATOR . './library/'
        . PATH_SEPARATOR . './services/'
        . PATH_SEPARATOR . './models/vo/'
        . PATH_SEPARATOR . './models/entities/'
        . PATH_SEPARATOR . get_include_path()
);
 
 
//inclui bibliotecas
require_once 'lumine-conf.php';
require_once 'Lumine/Lumine.php';
require_once 'Zend/Loader/Autoloader.php';
require_once 'ApplicationLoader.php';
 
 
 
//seta tempo infinito de execucao
set_time_limit(0);
 
//Mostrar todos os erros independente qual seja
error_reporting(E_ALL|E_STRICT);
 
// indica o timezone padrao
date_default_timezone_set('Brazil/East');
 
// auto-carregamento de classes de Lumine
spl_autoload_register(array('Lumine','Import'));
 
// auto-carregamento de classes DTO de Lumine
spl_autoload_register(array('Lumine','ImportDTO'));
 
// instancia uma configuracao do lumine
$cfg = new Lumine_Configuration($lumineConfig);
 
// registra uma funcao para o fechamento da conexao ao termino do script
register_shutdown_function(array($cfg->getConnection(),'close'));
 
// carregamento automatico das classes zend
Zend_Loader_Autoloader::getInstance();
 
// carregamento automatico das classes da aplicação
ApplicationLoader::getInstance();
 
$server = new Zend_Amf_Server();
$server->addDirectory('./services/');
$server->addDirectory('./models/vo/');
echo($server->handle());

lumine-conf.php

$lumineConfig = array(
        'dialect'   => 'MySQL',
        'port'      => '3306',
        'user'      => 'xxxx',
        'password'  => 'xxxx',
        'host'      => 'localhost',
        'database'  => 'lumine_zend_flex',
        'package'   => 'models.entities',
        'class_path'=> 'xxxx\www\lumine-zend-flex\php',
 
        'options' => array(
                'auto_cast_dto' => '1',
                'dto_format'    => '%sVO',
                'dto_package'   => 'models.vo',
        )
);

Com isso finalizamos a configuração da Base de dados, Lumine e ZendAmf.
Agora podemos partir para a configuração das nossas classes de modelo de dados:
Tutorial : Lumine + ZendAmf + Flex 2/5

Até já !!!

Tutorial : Lumine + ZendAmf + Flex 1/5
Tutorial : Lumine + ZendAmf + Flex 2/5
Tutorial : Lumine + ZendAmf + Flex 3/5
Tutorial : Lumine + ZendAmf + Flex 4/5
Tutorial : Lumine + ZendAmf + Flex 5/5

« Entradas anteriores |

tube8com
nudetubecom
xtube football toilette
redtube.com porn
porn tube
the tube
peg tube
cum swap tube
tube8 and beastiality
shush tube.com
famous pornstar tube
zoo tube 365
yuo tube porno
zootubecouk
tube xxx
rapetube
nikki blond filestube
zoo animal sex tube
zoosex tube 365
utube porn sites
hqtube
mature tube
gay porn tube
nudisten tube
shocking tube
porno tube xxx
dog sex tube
redtube
porn tube8
www.nude tube.com
4tube
8 tube
scat orgy tube 8
dancing xtube
twinksxtubeporn
tube x
zootubecom
animaal sex tube
psp sexy tubes
tubeteenscom
zoo sexe tube
london tube map
xtube gay jizz
pornhube
xtube spor
amateur porn tubes
beast tube
bondage and tube
adult tube sites
spankingtube
xtubecom
xtube rumen
panty pissing xtube
youporne
twin fuck tube
tivias tube
man tube
porno tube
tube8 video
hot tube
redtube4
test tubes
vacuum tube
jeans pissing xtube
ourtube
iyot tube
yoy tube
red.tube.com
bdsm tube
hqtubecom
amateur asian creampies red tube
crushfetishtube
free tube porn
anonymous redtube
blacktube
saving xtube videos
redtubecom
german porn tube
extreme tube porn
bestiality tube
rawtube
www red tubecom
beastiality tube
tube videos
redtube porn
eskimotube
teentube
xtube big brothers
zootube
redtube.eu
rocket tube
kick boxing xtube
download redtube videos
asian porn tube
free porn tubecom
xtube videos
brazzerstube.com
re tube
tubehentai
free sex tube
xtube cumming
hardtube
tube365 com
xxxtube
one tube oscillators
pornoytube
sextube videos
yuvutu
hard sex tube
tube8.c0m
lesbiantube
u tube nudes
fktube.com
www.tube8.com
wanktube
ube 8
tree tube
pronotube
bbw porntube
tiava
poh tube
black porn tubes
hentaitube
rredtube
lolita tube
innertube
gexo xtube
horse sex tube
yutube glasb
sex tube
porn tube.com
tubexxx
tuberculosis bacterium
dirtytube porn
xtube ball
TUBESEX
gas detection tube
zoo porn tube
free porn tube
xtube berlin
bootytube247
freedom tube
jizztube
pornotube x
tou tube
god tube
tit tube
british porn tube
skimtube
free psp tubes adult
beasttube zoo369
slut tube
zootube365
girls kissing on utube
sextube.com
sex tube sites
rede tube
mytube
xtube
celeb boob tube
granny tube
tube tops
rtube
pain tube
redtube competition digg
gaytube
shemale tube
sexy utube
zoo tube 365 com
sex tubes
red porn tube
xtube spy college
boob tube
solartube
tiavas tube
free web tube
homemoviestube.com
tube sex
pussy tube
snake tube xxx
urporntube
studded tube manufacturers
r tube
pornotub
porn hub
rudetube
milf tube
panty pissing xtube
blue tube
pornotube.com acount
lubetube
animals bestiality tube
nudetube
xxx porn tube
free porn tubes
yotube
fetish tube
free sextube video
free beast tube horse cum pussy
fuck tube
rdtube
tube for porn
tree tubes
reed tube
8 tube porn
erotic hot tube
x.tube.com
maturetube.com
adult tube movies
bangtubecom
zoo tube com
red tube videos
hotutubes
download xtube videos free
porn movie tube
croctube
uporntube
pinktube
incest porn tube
hq tube.com
ass nude tube
yu tube sexs
z porntube
sextube
sexytube.com
free extreme pornotube
utube enema viedo
xtube nudist beach
zootube porn
ebony porn tube
japanese porntube
lube tube
tubegals
besattube
enemas utube
tuberose essential oil
footfetishtube
animal bestiality porn tube
tube tube
porn tube sites
gay x tube videos
dude tube
xnxx.com
porn utube
japanese tits tube
utube videos
x tube
bizarre tube
filthtube
bang tube

ACERCA

O que é o RedeRIA ?

O redeRIA não é nada mais que um agregador de feed's que disponibiliza o conteudo de varios blogs e autores ao redor do mundo RIA, actualmente agregamos mais de 1394 entradas vindas de 40 blogs especializados em ria’s, pelo que só fica a ganhar em assinar o feed ou seguir a comunidade no twitter.

Se acha que o seu blog ou um blog de um amigo é interessante e util para os leitores o redeRIA, faça a sua submissão aqui.

Feed: assine já
Twitter: siga-nos
Versão Mobile: aceda aqui

GOOGLE

Votação


Deveria o redeRIA organizar algum evento sobre RIA's ?? Sobre quais plataformas?
Ver Resultados

AUTORES


Eduardo KrausAlexandreBindableDaniel LopesDClick TeamEbercomEdgard DavidsonElvis FernandesFabiel PrestesFábio Batista da SilvaFabio da SilvaFlavia MoreiraGabriela T. PerryIgor MusardoJanderson CardosoJose Carlos FielKelps SousaLeonardo FrançaLucas MarçalMario JuniorMário SantosMauro MartinsPedro ClaudioreneRia BrazilriaPTRicardo CerqueiraRobson FernandesRodrigo Pereira FragaSaintBrSergio SouzaSilva DeveloperStefan HorochovecTech CaffeTecinforThiago BuenoVedVinícius SandimXAML Cast

PUBLICIDADE








Powered by Wordpress & msdevstudio.com