Hoje criei um novo projeto no Github, para um plugin para jQuery (1.7+) que desenvolvi (estou e estarei desenvolvendo). Trata-se um scroller vertical que pode ser aplicado a qualquer tag block.
$('#news').vScroller({
width: 300,
height: 400
});
Conforme surgir demanda, necessidade de mais funcionalidades, callbacks, eu irei incrementando o projeto. Embora simples, está funcional, e serve como estudo.
[update 2012-01-24]
Features:
- MouseWheel
- Drag&Drop
- Keys (UP, DOWN, PG_UP, PG_DOWN, HOME, END)
Compatibility (tested):
- Chrome 12+
- Firefox 8+
- Opera 11+
[/update]
dochub concentra de maneira fácil e rápida as documentações de CSS, HTML, Javascript e DOM. No qual tem o seu conteúdo retirado da Mozilla Developer Network.
Excelente ferramente para tirar aquela dúvida ou refrescar a memória.
yepnope is an asynchronous conditional resource loader that’s super-fast, and allows you to load only the scripts that your users need.
Good Things
- yepnope.js is only 1.6kb – smaller than most and certainly a good size for its functionality set.
- yepnope.js is called a “resource loader” because it can work with both JavaScript and CSS.
- yepnope.js has a full test suite in QUnit that you can run in your set of supported browsers to make sure it works. (We run it via TestSwarm in every browser we can get our hands on)
- yepnope.js fully decouples preloading from execution. This means that you have ultimate control of when your resource is executed and you can change that order on the fly.
- The yepnope.js api is friendly and encourages logical grouping of resources.
- yepnope.js is modular. It has a whole system for adding your own functionality and a couple examples of how you might do that. (Prefixes and filters).
- The yepnope.js api encourages you to only load the resources that you need. This means that even when it’s slower than another script loader, it still can come out on top, because you could avoid an entire resource.
- yepnope.js is integrated into Modernizr.
- yepnope.js always executes things in the order they are listed. This is a pro for some, and a con for others. We think it’s a friendly default.
- yepnope.js has the capability to do resource fallbacks and still download dependent scripts in parallel with the first.
Criado o projeto para o framework Manga, no Github (PHP 5.3+).
Entre algumas funcionalidades, destaca-se o seu template engine baseado no Facelets.
Os arquivos de configuração poderão ser escritos em mais de um formato, inicialmente suporte a XML e YAML. Annotations são utilizadas para enxugar esses arquivos de configuração, deixando o código mais intuitivo.
O próximo passo é implementar suporte à IoC, que inicialmente pode ser simulado pelo arquivo de configuração de rotas (com suporte REST).
A intenção não é desenvolver um framework revolucionário, e sim adaptar as ideias e metodologias já utilizadas por outros em um único framework afim de aumentar a produtividade. Servem como inspiração os seguintes frameworks:
Ruby
Java
PHP
Para quem está utilizando o CakePHP ou já utilizou e também sentiu falta de herança nos layouts. Segue abaixo uma dica para ajudar na criações de templates utilizando o CakePHP.
<?php
// sublayout.ctp
ob_start();
?>
<?php eco $content_for_layout; ?>
<?php
$content = ob_get_contents();
ob_end_clean();
echo $this->renderLayout(
$content,
'default' // parent layout
);
<?php
// controller class
class MyController extends AppController {
function test() {
$this->layout = 'sublayout';
}
}
Todo mundo que programa em PHP sente falta de uma boa alternativa para separar o código PHP do visual (HTML). Nessas horas vale a pena estudar algumas template engines para PHP disponíveis para saber qual que melhor se adapta à suas necessidades e projeto. Alguns frameworks MVC possuem sua própria engine, outros tentam.
O mais famoso e usado como inspiração por muitos outros projetos. Robusto (possuindo blocos condicionais/loops e várias funções próprias) e rápido (“compilando” suas páginas para arquivos PHP).
<ul>
{foreach from=$myArray item=foo}
<li>{$foo}</li>
{/foreach}
</ul>
$smarty = new Smarty;
$arr = array(1000, 1001, 1002);
$smarty->assign ('myArray', $arr);
$smarty->display ('HelloWorld.tpl');
Com esta engine saímos de um problema e entramos em outro, é necessário aprender (lembrar) algumas palavras reservadas para sinalizar variáveis, além do uso dos limitadores das expressões.
<html>
<head>
<title>{tmpl_var name='title_text'}</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<p>{tmpl_var name='body_text'}</p>
</body>
</html>
$tmpl = new vlibTemplate('tmpl/basic.htm');
$tmpl->setvar('title_text', 'TITLE: This is the vLIB basic example ...');
$tmpl->setvar('body_text', 'BODY: This is the message set using setvar()');
$tmpl->pparse();
Muito pouco usual, o FXL faz uso dos blocos de comentário HTML para definir os loops. Outros semelhantes e nada melhores são: QuickSkin e XTemplate.
<table>
<!-- START row -->
<tr>
<!-- START cell -->
<td >{td_value} </td>
<!-- END cell -->
</tr>
<!-- END row -->
</table>
$fxlt = new fxl_template('example.tpl');
$fxlt_row = $fxlt->get_block('row');
$fxlt_cell = $fxlt_row->get_block('cell');
for ($tr = 1; $tr <= 3; $tr++) {
for ($td = 1; $td <= 3; $td++) {
$fxlt_cell->assign('td_value', $tr.':'.$td);
$fxlt_row->assign('cell', $fxlt_cell);
$fxlt_cell->clear();
}
$fxlt->assign('row', $fxlt_row);
$fxlt_row->clear();
}
$fxlt->display();
Mais do mesmo, mas com alterações de sintaxe.
<h1>{if:logged} Welcome {username} {else:} User not logged {end:} </h1>
<ul>
{foreach:rows,row}
<li>
{row['name']}
</li>
{end:}
</ul>
$t = new vemplator();
// if/else
$t->assign('logged', true);
$t->assign('username', 'Rogerio');
// loop
$items = array(
array('name' => 'Laptop'),
array('name' => 'Memory Stick')
);
$t->assign('rows', $rows);
echo $t->output('example.template.html');
Uma alternativa ao estilo Smarty de muitos, porém é mais confuso e segue um padrão de nomenclatura bem particular.
<table > <tr><td>[blk.val;block=tr]</td></tr> </table >
$TBS =& new clsTinyButStrong ;
$TBS->LoadTemplate('template.htm') ;
$list = array('X','Y','Z') ;
$TBS->MergeBlock('blk',$list) ;
$TBS->Show();
Possui como diferencial um Template Inheritance, o que facilita muito a vida na construção de templates.
<html>
<head>
<title>{block "title"}My site name{/block} </title>
</head>
<body>
<h1>{block "page-title"}Default page title{/block} </h1>
<div id="content">
{block "content"}
Welcome to my amazing homepage
{/block}
</div>
</body>
</html>
{extends "base.html"}
{block "title"}
Gallery
{/block}
{foreach $images img}
{/foreach}
$dwoo = Dwoo();
$images = array(
array('url' => 'img1.jpg', 'description' => 'Ferrari'),
array('url' => 'img2.jpg', 'description' => 'BMW')
);
$params = array();
$params['images'] = $images;
echo $dwoo->get("gallery.tpl", $params);
Baseado no Smarty, Django Templates e Jinja (os dois últimos para Python).
<html>
<head>
<title>{{ page.title }}</title>
</head>
<body>
{{ page.content }}
</body>
</html>
$h2o = new h2o('index.html');
$page = array(
'title' => 'title of a page',
'body' => 'Hello world'
);
echo $h2o->render(compact('page'));
Entre os projetos disponíveis no PEAR (PHPLIB, Sigma e IT) esse é o melhor.
Tem como desvantagem o fato de ter que definir as propriedades da sua classe como public (pelo menos dá para trabalhar com classes), linhas de includes e configurações exageradas (não presentes no exemplo abaixo), e algumas automações que precisam ser bem explicadas senão o programador (usuário) fica doido. Além de ter que codificar muito mais linhas se compararmos com os demais exemplos.
<html>
<head>
<title>{title}</title>
</head>
<body>
<!-- o valor do input será adicionado em $element['input'] -->
Input Box: <input name="input" />
<ul>
<!-- isso é o mesmo que foreach ($numbers as $number => $string) -->
<li flexy:foreach="numbers,number,string" >
<a href="mypage.html?id={number}">{string}</a>
</li>
</ul>
<!-- chamando o método da classe -->
{someMethod()}
</body>
</html>
class controller_test {
var $title;
var $numbers = array();
var $elements = array();
function controller_test() {
$this->start();
$this->output();
}
function start() {
$this->title = "Hello World";
// create an HTML Element for the form element.
$this->elements['input'] = new HTML_Template_Flexy_Element;
$this->elements['input']->setValue('Hello');
for ($i = 1;$i< 5;$i++) {
$this->numbers[$i] = "Number $i";
}
}
function output() {
$output = new HTML_Template_Flexy();
$output->compile("home.html");
$output->outputObject($this,$this->elements);
}
function someMethod() {
return "Hello From A Method";
}
}
new controller_test();
Todos os exemplos a cima foram retirados dos próprios sites dos projetos, sofrendo alterações afim de minimizar as linhas e focar em suas caracterísicas, vantagens e desvantagens.
Em meados do ano passado comecei escrever uma engine baseada no JSF+Facelets (Java) e nesse mês voltei a trabalhar nela e espero que no próximo ano (2011) já tenha uma versão liberada (farei um post sobre).
Comecei escrever um pequeno projeto para facilitar a criação de jogos em Javascript utilizando HTML5 Canvas para isso. Baseado em scenegraph podendo criar nós dependentes, relativos ao nó pai. Por enquanto a estrutura da engine é composta por:
Canvas: para encapsular a tag canvas, pegando automaticamente o context e fornecendo algumas funções a mais.
Game: o jogo em sí, possui uma ou muitas cenas (Scene). Contém o loop principal para atualizações do canvas. Necessita de uma instância do Canvas.
Scene: deve ser estendida para criar cenas customizadas, deve implementar o método update(interval).
CanvasNode: um nó do grafo, possui as coordenadas e ângulo de rotação do elemento no canvas.
CanvasNodeGroup: um grupo de nós. Estende CanvasNode.
Graphics: um nó “printável”, quem for estendê-lo deve implementar o método draw(). Possui como subclasses: Rectangle, Triangle, Circle, Text, Image2d e Line.
GraphicsGroup: estende CanvasNodeGroup, possui um grupo de graphics. Scene é um GraphicsGroup.
Os próximos passos serão a implementação de TileMap, Scene Intro, Menu e botões. Agora é só aguardar até o próximo exemplo.
[update 2010-05-06]
Added mouse and button support.
See example above.
[/update]
[update 2010-05-06]
Examples in http://mangame.rogeriolino.com/
[/update]
[update 2011-11-11]
Source now available in GitHub!
[/update]
Muitas linguagens oferecem suporte a Sockets, e com PHP não é diferente, porém a falta de orientação a objetos nas funções do PHP pode ser um inconveniente para algumas pessoas. E como eu me incluo entre essas pessoas, quando precisei utilizar sockets em PHP acabei criando um classe para englobar essas funções soltas e fornecer tratamento a erros.
/**
* Copyright 2010 Rogerio Alencar Lino Filho
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Socket
*
* @author rogeriolino
*/
class Socket {
private $port = 3000;
private $address = "localhost";
private $blocking = true;
private $buffer = 2048;
private $backlog = 5;
private $type = SOCK_STREAM;
private $family = AF_INET;
private $protocol = SOL_TCP;
private $resource;
/**
* Socket constructor
* @param $resource
*/
public function __construct($resource = null) {
if ($resource == null) {
$this->resource = socket_create($this->family, $this->type, $this->protocol);
} else {
$this->resource = $resource;
}
}
/**
* Returns the socket port
* @return int
*/
public function get_port() {
return $this->port;
}
/**
* Define the socket port
* @param int $port
*/
public function set_port($port) {
$this->port = $port;
}
/**
*
* @return string
*/
public function get_address() {
return $this->address;
}
public function set_address($address) {
$this->address = $address;
}
/**
* Returns if the socket is blocking mode
* @return boolean
*/
public function is_blocking() {
return $this->blocking;
}
/**
* Defines whether the socket is blocking or nonblocking mode
* @param boolean $block
*/
public function set_blocking($blocking) {
$this->blocking = ($blocking == true);
$this->update_blocking_mode();
}
/**
* Returns the socket communication type
* @return int
*/
public function get_type() {
return $this->type;
}
/**
* Define the socket communication type
* @param int $type
*/
public function set_type($type) {
if ($type == SOCK_STREAM || $type == SOCK_DGRAM || $type == SOCK_SEQPACKET || $type == SOCK_RAW || $type == SOCK_RDM) {
$this->type = $type;
} else {
throw new Socket_Exception("Invalid socket communication type");
}
}
/**
* Returns the socket protocol family
* @return int
*/
public function get_family() {
return $this->family;
}
/**
* Define the socket protocol family
* @param int $family
*/
public function set_family($family) {
if ($family == AF_INET || $family == AF_INET6 || $family == AF_UNIX) {
$this->family = $family;
} else {
throw new Socket_Exception("Invalid socket protocol family");
}
}
/**
* Returns the socket protocol
* @return int
*/
public function get_protocol() {
return $this->protocol;
}
/**
* Define the socket protocol, must be compatible whit the protocol family
* @param int $protocol
*/
public function set_protocol($protocol) {
if ($protocol == SOL_TCP || $protocol == SOL_UDP || $protocol == SOL_SOCKET) {
$this->protocol = $protocol;
} else {
throw new Socket_Exception("Invalid socket protocol");
}
}
/**
* Binds to a socket
* @throws Socket_Exception
*/
public function bind() {
if (socket_bind($this->resource, $this->address, $this->port) === false) {
throw new Socket_Exception("Socket bind failed: " . $this->error());
}
}
/**
* Listens for a connection on a socket
* @throws Socket_Exception
*/
public function listen() {
if (socket_listen($this->resource, $this->backlog) === false) {
throw new Socket_Exception("Socket listen failed: " . $this->error());
}
}
/**
* Accepts a connection
* @throws Socket_Exception
* @return Socket
*/
public function accept() {
$sock = socket_accept($this->resource);
if ($sock === false) {
throw new Socket_Exception("Socket accept failed: " . $this->error());
}
return new Socket($sock);
}
/**
* Reads data from the connected socket
* @return string
*/
public function read() {
$data = "";
while (($m = socket_read($this->resource, $this->buffer)) != "") {
$data .= $m;
}
return $data;
}
/**
* Write the data to connected socket
* @param string $message
*/
public function write($data) {
socket_write($this->resource, $data, strlen($data));
}
/**
* Initiates a connection on a socket
* @throws Socket_Exception
* @return boolean
*/
public function connect() {
try {
return socket_connect($this->resource, $this->address, $this->port);
} catch (Socket_Exception $e) {
return false;
}
}
/**
* Close the socket connection
*/
public function close() {
socket_close($this->resource);
}
private function update_blocking_mode() {
if ($this->blocking) {
socket_set_block($this->resource);
} else {
socket_set_nonblock($this->resource);
}
}
private function error() {
return socket_strerror(socket_last_error($this->resource));
}
}
Classe para as exceções:
/**
* Copyright 2010 Rogerio Alencar Lino Filho
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Socket_Exception
*
* @author rogeriolino
*/
class Socket_Exception extends Exception {
public function __construct($message, $code = 0, $previous = null) {
$this->message = $message;
$this->code = $code;
$this->message = $previous;
}
}
Espero que seja de bom aproveito.
- SVG Wow Demos
- Code Bubbles: Rethinking the User Interface Paradigm of IDEs
- JSON visualization tool
- Reloading Java Classes: HotSwap and JRebel – Behind the Scenes
- Justiça volta a incluir Anatel como ré em processo que questiona banda larga
- HTML5 Database
- Valve Brings Hit Games, Steam Service to Mac
- Bespin Code in the Cloud
- Com novo roteador, Cisco promete turbinar internet do futuro
- Google Island e a banda larga ultrarrápida
- The Reddit problem: Learning from mistakes
- NoSQL v. SQL is the worst holy war ever.




