Professional Documents
Culture Documents
ndice
Gua de usuario de ZanPHP Informacin Bsica Inicio Requerimientos del Servidor Descarga Licencia de Uso Crditos
Temas Generales Estructura de Archivos Configuracin Bases de Datos Aplicaciones Controladores Vistas Modelos Traducciones
Referencia de las Clases Clase Array2XML Clase Cache Clase Controller Clase Data Clase Db Clase Email Clase Files Clase Images Clase Load Clase Log Clase Model Clase MongoDB
Clase Pagination Clase RESTClient Clase RESTServer Clase Singleton Clase Templates
Referencia de los Ayudantes Ayudante Alerts Ayudante Array Ayudante Autoload Ayudante Benchmark Ayudante Browser Ayudante Debugging Ayudante Forms Ayudante HTML Ayudante il8n Ayudante Inflect Ayudante Router Ayudante Security Ayudante Sessions Ayudante String Ayudante Time Ayudante Validations
Inicio
ZanPHP es un framework de desarrollo gil de aplicaciones Web escrito en PHP5 el cual utiliza distintos patrones de diseo y las mejores prcticas para crear aplicaciones ms rpidamente y con buena calidad de cdigo. Algunas de las ventajas de ZanPHP son las siguientes: Fcil de instalar y configurar Fcil de aprender Puedes crear casi cualquier tipo de aplicaciones Web Compatible con distintas plataformas Orientado a objetos Utiliza gran cantidad de patrones de diseo y las mejores prcticas para producir cdigo de mayor calidad Aplicaciones escalables y fciles de mantener Documentacin en Ingls y Espaol Integracin con jQuery y jQuery Mobile, Ajax y otras nuevas tecnologas Es Software Libre
Descarga
Puedes descargar el ZanPHP desde GitHub.com. Clonando el repositorio git clone git://github.com/MilkZoft/ZanPHP.git Descarga directa https://github.com/MilkZoft/ZanPHP/downloads
Licencia de Uso
Copyright (c) 2011, MilkZoft, Inc. Todos los derechos reservados. Esta licencia es un acuerdo legal entre usted y MilkZoft, Inc. para el uso de Software ZanPHP (el "Software"). Al obtener el Software, usted acepta cumplir con los trminos y condiciones de esta licencia. USO PERMITIDO Usted est autorizado para usar, copiar, modificar y distribuir el Software y su documentacin, con o sin modificaciones, para cualquier propsito, siempre que se cumplan los siguientes requisitos: 1. Una copia de este acuerdo de licencia debe ser incluido con la distribucin. 2. La redistribucin del cdigo fuente deben conservar el aviso de copyright en todos los archivos de cdigo fuente. 3. Las redistribuciones en formato binario deben reproducir el aviso de copyright en la documentacin y / o otros materiales suministrados con la distribucin. 4. Todos los archivos que han sido modificados deben llevar avisos indicando la naturaleza de los cambios y los nombres de aquellos que los cambi. 5. Productos derivados del Software debe incluir un reconocimiento que se derivan de ZanPHP en su documentacin y / o otros materiales suministrados con la distribucin. 6. Productos derivados del Software no puede ser llamado "ZanPHP", ni podr aparecer "ZanPHP" en su nombre, sin la previa autorizacin por escrito de MilkZoft, Inc. INDEMNIZACIN Usted acepta indemnizar y mantener indemne a los autores del Software y todos los colaboradores por los daos directos, indirectos, incidentales o consecuentes reclamaciones de terceros, acciones o demandas, as como cualquier gasto, responsabilidades, daos, asentamientos o cargos derivados de su uso o mal uso del Software, o una violacin de cualquiera de los trminos de esta licencia. RENUNCIA DE GARANTA EL SOFTWARE SE ENTREGA "TAL CUAL", SIN GARANTA DE NINGN TIPO, EXPRESA O IMPLCITA, INCLUYENDO, PERO NO LIMITADO A, LAS GARANTAS DE CALIDAD, RENDIMIENTO, NO INFRACCIN, COMERCIALIZACIN O IDONEIDAD PARA UN PROPSITO PARTICULAR.
LIMITACIONES DE LA RESPONSABILIDAD USTED ASUME TODO RIESGO ASOCIADO CON LA INSTALACIN Y EL USO DEL SOFTWARE. EN NINGN CASO LOS AUTORES O TITULARES DEL SOFTWARE SE HACE RESPONSABLE DE LAS RECLAMACIONES, DAOS O CUALQUIER OTRA
RESPONSABILIDAD QUE SE PRESENTE, DE, O EN RELACIN CON EL SOFTWARE. LOS TITULARES DE LICENCIAS SON LOS UNICOS RESPONSABLES DE DETERMINAR LA CONVENIENCIA DE UTILIZACIN Y ASUME LOS RIESGOS ASOCIADOS CON SU USO, INCLUYENDO PERO NO LIMITADO A LOS RIESGOS DE LOS ERRORES DEL PROGRAMA, DAOS AL EQUIPO, PRDIDA DE DATOS O PROGRAMAS DE SOFTWARE, O FALTA DE DISPONIBILIDAD O DE LA INTERRUPCIN DE LAS OPERACIONES.
Crditos
ZanPHP fue desarrollado por Carlos Santana (CEO de MilkZoft). ZanPHP fue desarrollado en 2009, pero hasta Julio de 2011 se tomo la decisin de liberarlo como software libre. Actualmente el desarrollo de ZanPHP es mantenido por el equipo de desarrollo de MilkZoft y por los colaboradores de la comunidad. Se implementaron las mejores prcticas para desarrollar aplicaciones de manera ms rpida y con mayor calidad. El equipo de desarrollo que conforma a MilkZoft, es el siguiente:
Primeros Pasos
Para empezar a trabajar con ZanPHP, el primer paso necesario es: descargarlo. Obtener ZanPHP es muy fcil, slo hay que descargarlo desde: https://github.com/MilkZoft/ZanPHP o clonarlo con git utilizando el comando: git clone git://github.com/MilkZoft/ZanPHP.git
El siguiente paso es configurar unas constantes de 2 archivos de configuracin, estos archivos deben ser renombrados (quitarles la extensin .example). Estos archivos se encuentran en: /www/config El primer archivo a modificar es el de /www/config/config.php donde se debern modificar las siguientes variables: $ZP[domain]: nos sirve para especificar el dominio que nuestro sitio tendr. $ZP[modRewrite]: activa o desactiva la estilizacin de URLs (TRUE o FALSE). $ZP[webURL]: nos permite configurar la URL general que tendr el sitio, til para cargar imagenes, scripts, etc. $ZP[defaultApplication]: permite configurar la aplicacin principal del sitio $ZP[webSituation]: configura el acceso al sitio web (Active or Inactive) $ZP[webLanguage]: configura el idioma por defecto del sitio web
El segundo archivo a configurar es /www/config/database.php, en las siguientes variables: $ZP[dbDriver]: nos permite especificar el controlador de base de datos a utilizar. $ZP[dbHost]: nos permite configurar el host donde se encuentra el servidor de base de datos (usualmente es localhost) $ZP[dbUser]: el usuario para conectarnos a la base de datos. $ZP[dbPwd]: la contrasea para conectarnos a la base de datos. $ZP[dbName]: el nombre de la base de datos a la cual nos vamos a conectar. $ZP[dbPort]: el puerto de conexin. $ZP[dbPfx]: el prefijo que nuestras tablas tendrn.
Una vez realizados estos pasos, ya tenemos listo ZanPHP para trabajar, solo es cuestin de empezar a crear aplicaciones.
Controlador Esta clase es el administrador del flujo de la aplicacin, se encarga de recibir las peticiones del usuario, identificarlas, procesarlos, mandar a llamar a los mtodos del modelo necesarias y retornar los datos al usuario por medio de una vista. Los controladores deben estar ubicadas en el directorio /controllers de cada aplicacin.
Estructura de Archivos
www Este directorio es el que contiene todas las aplicaciones desarrolladas con ZanPHP, adems de incluir tambin la librera de archivos, en ella se encuentran diferentes tipos de archivos, entre los que destacan: hojas de estilo, libreras externas, plantillas, imgenes, as como los archivos subidos por cada aplicacin. zan El directorio "zan" es el ms importante de ZanPHP, pues en el se encuentran los archivos de configuracin del sitio a desarrollar, as, como las clases importantes del framework que soportan la arquitectura del mismo, las traducciones, as como todas las funciones (helpers) que el framework nos ofrece para realizar el trabajo pesado.
Bases de Datos
Gracias a los patrones de diseo que ZanPHP implementa, es posible utilizar ms de un controlador de base de datos en nuestros sitios, esto quiere decir que podemos trabajar en un sitio bajo MySQL, SQL Server, Postgre SQL y bases de datos NoSQL cmo MongoDB. Para esto, slo es necesario, modificar la variable $ZP[dbDriver] ubicada en el
archivo: /www/database.php.
Aplicaciones
Crear una aplicacin en ZanPHP es muy fcil, solo es necesario crear un directorio dentro de applications/, el directorio deber llevar el nombre de la aplicacin en minsculas, y dentro de este las carpetas controllers, models y views. Estructura bsica de una aplicacin applications/ blog/ controllers blog.php comments.php
comments.php posts.php
Controladores
Los controladores en ZanPHP son muy importantes pues son indispensables para la utilizacin del MVC. Es muy importante que cada aplicacin debe de tener un controlador, un modelo y las vistas pueden variar. Ahora bien, en esta seccin se analizar la estructura que un controlador debe de tener para su correcto funcionamiento:
class MyApplication_Controller extends ZP_Controller { public function __construct() { $this->Templates = $this->core("Templates"); $this->MyApplication_Model = $this>model("MyApplication_Model"); $this->helpers(); $this->Templates->theme(_webTheme); } public function index() { print __("Hi, I'm MyApplication"); } }
Esta es la estructura bsica que cualquier controlador debera tener y cumplir para el correcto funcionamiento del framework.
Vistas
Las vistas son las encargadas de mostrar o solicitar datos al usuario. El controlador es el encargado de cargar las vistas con los datos obtenidos mediante los modelos. As es como funciona el patrn de diseo MVC. Las vistas deben estar ubicadas en el directorio /views de cada aplicacin. Otro aspecto importante para mencionar acerca del directorio /views, es que dentro de este pueden crearse los directorios /css, /js o /images; donde debern de ser colocados las hojas de estilos, scripts e imgenes que sern utilizadas nicamente por la aplicacin.
Modelos
Los modelos son pieza fundamental de una aplicacin, pues son los que se encargan de interactuar con la base de datos, modelar, clasificar y hasta organizar los datos. Al igual que los controladores poseen una estructura bsica que debe de ser cumplida para trabajar correctamente con ZanPHP:
class MyApplication_Model extends ZP_Model { public function __construct() { $this->Db = $this->db(); $this->helpers(); $this->table = "mytable"; } }
Esta es la estructura bsica que cualquier controlador debera tener y cumplir para el correcto funcionamiento del framework.
Traducciones
ZanPHP implementa dos formas de traduccin, la primera utilizando GetText y la segunda con una manera manual. La forma para traducir con Gettext se utiliza de la siguiente forma:
constante _translation que esta en el archivo www/config/config.basics.php y ponerle como valor "normal". Para este tipo de traduccin solo ser necesario utilizar la funcin __().
Clase Array2XML
zan/classes/array2xml.php
Contenido
1 Cargando esta clase 2 Atributos 3 build($array, $ID) 4 checkForHTML($string) 5 printXML($array, $root = "data", $ID = "node") 6 toXML($array, $root = "data", $ID = "node")
$this->Array2XML = $this->core("Array2XML");
Atributos
@var private $XML = NULL
build($array, $ID)
Genera el XML.
checkForHTML($string)
Verifica si algn nodo contiene HTML.
$this->Array2XML = $this->core("Array2XML"); $data = array( 0 => array( "name" => "Carlos Santana", "email" => "carlos@milkzoft.com" ), 1 => array( "name" => "Carlos Hugo", "email" => "carlos.hugo@milkzoft.com" ), ); $this->Array2XML->printXML($data, "data", "contact");
//Prints <?xml version="1.0" encoding="UTF-8"?> <data> <contact> <name>Carlos Santana</name> <email>carlos@mlkzoft.com</email> </contact> <contact> <name>Carlos Hugo</name> <email>carlos.hugo@mlkzoft.com</email> </contact> </data>
Clase Cache
zan/classescache.php
Contenido
1 Cargando esta clase 2 Atributos 3 checkExpiration($expirationTime) 4 checkIntegrity($readHash, $serializedData) 5 delete($dir) 6 get($ID, $groupID = "default") 7 getKey($ID) 8 getStatus() 9 remove($ID, $groupID = "default", $groupLevel = FALSE) 10 removeAll($groupID = "default") 11 save($data, $ID, $groupID = "default", $time = _cacheTime) 12 setFileRoutes($ID, $groupID) 13 setStatus($status)
$this->Cache = $this->core("Cache");
Atributos
@var @var @var @var @var private private private private private $file = NULL $filename = NULL $filePath = NULL $groupPath = NULL $status = NULL
checkExpiration($expirationTime)
Verifica si el cache ha expirado.
checkIntegrity($readHash, $serializedData)
delete($dir)
Elimina el cache especficado, este mtodo es mandado a llamar por los mtodos remove() y removeAll().
getKey($ID)
Obtiene el hash del $ID por medio de la funcin sha1().
getStatus()
Obtiene el estado del cache, recuerde que deber poner en TRUE la constante _cacheStatus (www/config/config.cache.php).
$this->Cache->remove($ID, $groupID);
removeAll($groupID = "default")
Elimina el cache de todo un grupo sin tomar en cuenta IDs especficos.
$this->Cache->removeAll();
setFileRoutes($ID, $groupID)
Inicializa las rutas dnde se guardar el cache.
setStatus($status)
Clase Controller
zan/classes/controller.php
helpers()
Carga por defecto los helpers: alerts, debugging, files, time, string, security y validations.
Clase Data
zan/classes/data.php
Esta clase permite procesar la informacin enviada por formularios de una manera ms sencilla y rpida.
Contenido
1 Cargando esta clase 2 change($field, $newField) 3 ignore($field = FALSE) 4 proccess($data = NULL, $validations = FALSE) 5 rename($field) 6 table($table)
$this->Data = $this->core("Data");
//Checks if a publication exists with the following criteria $validations = array( "exists" => array( "Slug" => slug(POST("title", "clean")), "Year" => date("Y"), "Month" => date("m"), "Day" => date("d"), "Language" => POST("language") ), "title" => "required", "content" => "required" ); $this->Data->ignore(array("categories", "tags", "mural_exists", "mural", "pwd", "category", "language_category", "application")); $this->data = $this->Data->proccess($data, $validations); //If it causes an error, return a warning, if not, inserts the data. if(isset($this->data["error"])) { return array("error" => TRUE, "alert" => $this>data["error"]); } else { $this->Db->insert("blog", $this->data); }
rename($field)
Renombra los campos para poder ser insertados en la base de datos. Ejemplo: id_post lo renombrara a ID_Post.
table($table)
Selecciona una tabla de una base de datos con la clase Db.
Clase Db
zan/classes/db.php
Contenido
1 Cargando esta clase 2 Atributos 3 __construct() 4 begin() 5 cache($status = FALSE) 6 call($procedure) 7 close() 8 columns($table) 9 commit() 10 connect() 11 countAll($table = NULL) 12 countBySQL($SQL, $table = NULL) 13 data($query) 14 delete($ID = 0, $table = NULL) 15 deleteBy($field = NULL, $value = NULL, $table = NULL, $limit = 1) 16 deleteBySQL($SQL = NULL, $table = NULL) 17 encode($encode = TRUE) 18 encoding($rows) 19 fetch($count = 0) 20 fetchMode($fetch = "assoc") 21 find($ID, $table = NULL) 22 findAll($table = NULL, $group = NULL, $order = NULL, $limit = NULL) 23 findBy($field = NULL, $value = NULL, $table = NULL, $group = NULL, $order = NULL, $limit = NULL) 24 findBySQL($SQL, $table = NULL, $group = NULL, $order = NULL, $limit = NULL) 25 findFirst($table = NULL)
26 findLast($table = NULL) 27 free() 28 from($table) 29 get($table = NULL, $limit = 0, $offset = 0) 30 getTable($table) 31 getWhere($table, $where, $limit = 0, $offset = 0) 32 insert($table, $data) 33 insertBatch($table, $data) 34 insertID($table = NULL) 35 join($table, $condition, $position = FALSE) 36 like($data, $match = NULL, $position = "both") 37 notLike($data, $match = FALSE, $position = "both") 38 orLike($data, $match = FALSE, $position = "both") 39 orWhereIn($field, $data) 40 orWhereNotIn($field, $data) 41 query($query) 42 rollBack() 43 rows() 44 save($option = NULL) 45 select($fields = "*", $normal = TRUE) 46 selectAvg($field, $as = NULL) 47 selectMax($field, $as = FALSE) 48 selectMin($field, $as = NULL) 49 selectSum($field, $as = NULL) 50 table($table, $fields = "*") 51 update($table = NULL, $fields = NULL, $ID = 0) 52 updateBySQL($table = NULL, $SQL = NULL) 53 values($values) 54 where($data, $value = NULL) 55 whereIn($field, $data) 56 whereNotIn($field, $data) 57 whereOr($data, $value = NULL)
$this->Db = $this->db();
Atributos
@var @var @var @var @var @var @var @var @var @var @var @var @var @var @var @var private private private private private private private private private private private private private private private private $caching = FALSE static $connection = FALSE $encode = TRUE $fetchMode = "assoc" $fields $inserts = 0 $join $primaryKey = FALSE $query $row $Rs = NULL $select = "SELECT *" $SQL = NULL $table $values $where = NULL
__construct()
Se encarga de cargar la clase Cache, el archivo de configuracin "database", el archivo y el helper de excepciones y manda a llamar al mtodo connect().
begin()
Manda a llamar al mtodo begin() de la clase del controlador de base de datos correspondiente.
cache($status = FALSE)
Inicializa el atributo $this->caching, por defecto el cache est inactivo.
call($procedure)
Ejecuta un procedimiento almacenado y los valores los retorna en forma de array asociativo.
close()
Cierra la conexin a la base de datos.
columns($table)
Obtiene las columnas de una tabla y las retorna en forma de array asociativo.
$data = $this->Db->columns("mytable");
commit()
Manda a llamar al mtodo commit() de la clase del controlador de base de datos correspondiente.
connect()
Selecciona el driver especficado en el archivo de configuracin de bases de datos y carga la clase correspondiente al controlador, pudiendo ser MsSQL, MySQL, MySQLi, PgSQL, entre otros, y despus realiza la conexin.
countAll($table = NULL)
Retorna el total de registros de una tabla especficada, se puede especficar directamente la tabla o utilizar el mtodo table().
$count = $this->Db->countAll("mytable");
data($query)
Se encarga de procesar las consultas SQL y obtener los resultados en manera de vector, los datos por defecto sern pasados a la funcin encoding() y nos retornar siempre una matriz de resultados, este mtodo no se utiliza directamente, los dems mtodos lo mandan a llamar. Retorna una matriz como la siguiente:
array(2) { ["ID"] => int(1) ["Field"] => string(5) "Value" } [1] => array(2) { ["ID"] => int(2) ["Field"] => string(5) "Other Value" } }
$this->Db->delete(1, "contacts");
$this->Db->table("contacts"); $this->Db->delete(1);
$this->table("students");
encode($encode = TRUE)
Inicializa el atributo $this->encode, por defecto esta en TRUE.
encoding($rows)
Si el atributo $this->encode esta en TRUE, el mtodo encoding se encargar de procesar la informacin obtenida de la base de datos para pasarla por medio de la funcin encode() del helper string.
fetch($count = 0)
Manda a llamar al mtodo fetch() del controlador de base de datos correspondiente, retorna un array asociativo, escalar o un objeto, todo depende de lo que se especfique en el mtodo fetchMode(), por defecto retornar un array asociativo.
fetchMode($fetch = "assoc")
Especfica el modo que sern retornados los valores obtenidos de las tablas, por defecto esta especficado "assoc" lo que nos retornar un array asociativo.
$data = $this->Db->findAll("users");
findBy($field = NULL, $value = NULL, $table = NULL, $group = NULL, $order = NULL, $limit = NULL)
Encuentra uno o varios registros por medio de un campo y valor, se puede especficar la tabla o utilizar el mtodo table().
findFirst($table = NULL)
Encuentra el primer registro de una tabla.
$data = $this->Db->findFirst("users");
findLast($table = NULL)
Encuentra el ltimo registro de una tabla.
$data = $this->Db->findLast("users");
free()
Libera memoria despus de una consulta SQL.
from($table)
Selecciona una tabla.
$this->Db->from("mytable");
$this->Db->select("Username, Email"); $this->Db->from("users"); $this->Db->where("Username = 'ZanPHP' AND Pwd = '99b84460aa941d668e60262be137c7187045ed45'"); $data = $this->Db->get();
getTable($table)
Transforma una tabla especficada, le concatena el prefijo (_dbPfx) especficado en el archivo de config.database.php
$where = array( "Username" => "ZanPHP", "Pwd" => "99b94460aa941d668e60262be137c7187045fd45" ); //SELECT * FROM zan_users WHERE Username = 'ZanPHP' AND Pwd = '99b94460aa941d668e60262be137c7187045fd45' $data = $this->Db->getWhere("users", $where);
insert($table, $data)
Inserta un registro en una tabla.
//INSERT INTO zan_users (Username, Pwd, Email) VALUES ('ZanPHP', '99b94460aa941d668e60262be137c7187045fd45', 'webmaster@zanphp.com') $this->Db->insert("users", $data);
insertBatch($table, $data)
Inserta varios registros en una tabla.
$data = array( 0 => array( "Username" => "ZanPHP", "Pwd" => "99b94460aa941d668e60262be137c7187045fd45", "Email" => "webmaster@zanphp.com" ), 1 => array( "Username" => "CZantany", "Pwd" => "5679sad6sdfdf941d66gffg3560dfg187045fd47", "Email" => "czantany@zanphp.com" ), ); /* * INSERT INTO zan_users (Username, Pwd, Email) VALUES * ('ZanPHP', '99b94460aa941d668e60262be137c7187045fd45', 'webmaster@zanphp.com'), * ('CZantany', '5679sad6sdfdf941d66gffg3560dfg187045fd47', 'czantany@zanphp.com') */ $this->Db->insertBatch("users", $data);
insertID($table = NULL)
Retorna el ltimo ID insertado.
//INSERT INTO zan_users (Username, Pwd, Email) VALUES ('ZanPHP', '99b94460aa941d668e60262be137c7187045fd45', 'webmaster@zanphp.com') $this->Db->insert("users", $data); //If is the first record then return 1 $lastID = $this->Db->insertID();
$this->Db->select("*"); $this->Db->from("blog"); $this->Db->join("comments", "comments.ID_Comment = blog.ID_Post"); //SELECT * FROM blog JOIN comments ON comments.ID_Comment = blog.ID_Post $data = $this->Db->get();
$this->Db->select("*"); $this->Db->from("blog"); $this->Db->like("Title", "ZanPHP"); //SELECT * FROM zan_blog WHERE Title LIKE '%ZanPHP%' $data = $this->Db->get();
"Content" => "ZanPHP" ); $this->Db->like($data); //SELECT * FROM zan_blog WHERE Title LIKE '%ZanPHP%' AND Content LIKE '%ZanPHP%' $data = $this->Db->get();
$this->Db->select("*"); $this->Db->from("blog"); $this->Db->like("Title", "ZanPHP", "before"); //SELECT * FROM zan_blog WHERE Title LIKE '%ZanPHP' $data = $this->Db->get();
$this->Db->select("*"); $this->Db->from("blog"); $this->Db->like("Title", "ZanPHP", "after"); //SELECT * FROM zan_blog WHERE Title LIKE 'ZanPHP%' $data = $this->Db->get();
$this->Db->select("*"); $this->Db->from("blog"); $this->Db->notLike("Title", "ZanPHP"); //SELECT * FROM zan_blog WHERE Title NOT LIKE '%ZanPHP%' $data = $this->Db->get();
$this->Db->select("*"); $this->Db->from("blog"); $data = array( "Title" => "ZanPHP", "Content" => "ZanPHP" );
$this->Db->orLike($data); //SELECT * FROM zan_blog WHERE Title LIKE '%ZanPHP%' OR Content LIKE '%ZanPHP%' $data = $this->Db->get();
orWhereIn($field, $data)
Te ayuda a crear consultas tipo WHERE IN pero utilizando OR.
$this->Db->select("*"); $this->Db->from("users"); $this->Db->where("Username", "Carlos"); $users = array("ZanPHP", "CZantany", "Max"); $this->Db->orWhereIn("Username", $users); //SELECT * FROM zan_users WHERE Username = 'Carlos' OR Username IN ("ZanPHP", "CZantany", "Max") $data = $this->Db->get();
orWhereNotIn($field, $data)
Genera una consulta del tipo NOT IN.
$this->Db->select("*"); $this->Db->from("users"); $this->Db->where("Username", "Carlos"); $users = array("ZanPHP", "CZantany", "Max"); $this->Db->orWhereNotIn("Username", $users); //SELECT * FROM zan_users WHERE Username = 'Carlos' OR Username NOT IN ("ZanPHP", "CZantany", "Max") $data = $this->Db->get();
query($query)
Ejecuta una consulta libre.
rollBack()
Manda a llamar el mtodo rollBack() del controlador de la base de datos correspondiente.
rows()
Retorna el nmero de registros encontrados en una consulta.
save($option = NULL)
Realiza distintas acciones segn la opcin pasada como parmetro. Si se le pasa NULL, insertar un registro, si se le pasa un ID, mandar a llamar al mtodo update(), y si se le pasa un FALSE, mandar a llamar al mtodo updateBySQL().
$this->table("blog", "Title, Content"); $this->values("'Welcome to ZanPHP', 'Hi, welcome to ZanPHP website!'"); $this->save();
$this->table("blog"); $this->values("Title = 'Welcome to ZanPHP Part 2', Content = 'Hi, welcome to ZanPHP website! part 2.'"); $this->save(1);
$this->table("blog"); $this->values("Title = 'Welcome to ZanPHP Part 2', Content = 'Hi, welcome to ZanPHP website! part 2.' WHERE Slug = 'welcometo-zanphp'"); $this->save(FALSE);
//UPDATE zan_users SET Username = 'ZanPHP2', Email = 'webmaster2@zanphp.com' WHERE ID_User = 1 $this->Db->update("users", $data, 1);
//UPDATE zan_blog SET Title = 'New Title', Slug = 'new-title' WHERE Slug = 'old-title' LIMIT 1 $this->Db->updateBySQL("blog", "Title = 'New Title', Slug = 'new-title' WHERE Slug = 'old-title' LIMIT 1");
values($values)
Asigna valores al atributo $this->values.
$this->Db->select("Username"); $this->Db->from("users"); $this->Db->where("Email = 'contact@milkzoft.com'"); //SELECT Username FROM zan_users WHERE Email = 'contact@milkzoft.com' $data = $this->Db->get();
whereIn($field, $data)
Te ayuda a construir consultas tipo WHERE IN.
$this->Db->select("*"); $this->Db->from("users"); $users = array("ZanPHP", "CZantany", "Max"); $this->Db->whereIn("Username", $users); //SELECT * FROM zan_users WHERE Username IN ("ZanPHP", "CZantany", "Max") $data = $this->Db->get();
whereNotIn($field, $data)
Te ayuda a construir consultas tipo WHERE NOT IN.
//SELECT * FROM zan_users WHERE Username NOT IN ("ZanPHP", "CZantany", "Max") $data = $this->Db->get();
$this->Db->select("*"); $this->Db->from("users"); $this->Db->where("Username", "Carlos"); $this->Db->whereOr("Username", "ZanPHP"); //SELECT * FROM zan_users WHERE Username = 'Carlos' OR Username = "ZanPHP" $data = $this->Db->get();
$this->Db->select("*"); $this->Db->from("users"); $data = array( "Username" => "Carlos", "Username" => "ZanPHP" ); $this->Db->whereOr($data); //SELECT * FROM zan_users WHERE Username = 'Carlos' OR Username = "ZanPHP" $data = $this->Db->get();
Clase Email
zan/classes/email.php
$this->Email = $this->core("Email");
Atributos
@var @var @var @var @var public public public public public $email $fromName $fromEmail $message $subject
send()
Enva un Email.
$this->Email = $this->core("Email"); $this->Email->setLibrary("native"); $this->Email->fromName = "Joe Doe"; $this->Email->fromEmail = "me@example.com"; $this->Email->email = "for@example.com"; $this->Email->subject = "This is a Subject"; $this->Email->message = "This is the Message (able to contain HTML)"; $this->Email->send();
Clase Files
zan/classes/files.php
1 Cargando esta clase 2 Atributos 3 __construct() 4 getType($ext, $mimeType = FALSE, $return = FALSE, $icons = FALSE) 5 upload($path = NULL, $type = "image") 6 updateImage($dir, $inputName = "file", $type = "resize", $small = TRUE, $medium = TRUE, $original = TRUE)
$this->Files = $this->core("Files");
Atributos
@var @var @var @var @var public public public public public $fileError $filename $fileSize $fileTmp $fileType
__construct()
Carga los archivos de configuracin de files e images.
$this->Files = $this->core("Files"); //Assuming $_FILES["file"] is set and its a .rar file $this->Files->fileType = FILES("file", "type"); //Prints: "document"
$this->Files->getType($this->Files->fileType);
$this->Files = $this->core("Files"); $path = "path/to/"; //Assuming $_FILES["file"] is set and its a .rar file $this->Files->filename = FILES("file", "name"); $this->Files->fileType = FILES("file", "type"); $this->Files->fileSize = FILES("file", "size"); $this->Files->fileError = FILES("file", "error"); $this->Files->fileTmp = FILES("file", "tmp_name"); //Uploading... $this->Files->upload($path, "document");
updateImage($dir, $inputName = "file", $type = "resize", $small = TRUE, $medium = TRUE, $original = TRUE)
Sube y redimensiona una imagen.
$this->Files = $this->core("Files"); $path = "path/to/file"; //Assuming $_FILES["file"] is set and its an image (jpg, gif, png, etc.) file $this->Files->uploadImage($path, "file", "resize"); //Uploads: // /path/to/small_file.jpg // /path/to/medium_file.jpg // /path/to/original_file.jpg
Clase Images
zan/classes/images.php
1 Cargando esta clase 2 Atributos 3 getHeight() 4 getResize($size, $dir, $filename, $max = 0, $min = 0) 5 getWidth() 6 load($filename) 7 output($imageType = IMAGETYPE_JPEG) 8 resize($width, $height) 9 resizeToHeight($height) 10 resizeToWidth($width) 11 save($filename, $image_type = IMAGETYPE_JPEG, $compression = 75, $permissions = NULL) 12 scale($scale)
$this->Images = $this->core("Images");
Atributos
@var public $image @var public $imageType
getHeight()
Obtiene el alto de una imagen en pixeles.
$this->Files = $this->core("Files"); $this->Files->filename $this->Files->fileType $this->Files->fileSize $this->Files->fileError $this->Files->fileTmp = = = = = FILES("file", FILES("file", FILES("file", FILES("file", FILES("file", "name"); "type"); "size"); "error"); "tmp_name");
$dir = _www . _sh . _lib . _sh . _files . _sh . _images . _sh . _gallery . _sh . "myalbum" . _sh; $upload = $this->Files->upload($dir); if($upload["upload"]) { $this->Images = $this->core("Images"); $original = $this->Images->getResize("original", $dir, $upload["filename"], _minOriginal, _maxOriginal); $medium = $this->Images->getResize("medium", $dir, $upload["filename"], _minOriginal, _maxOriginal); $small = $this->Images->getResize("small", $dir, $upload["filename"], _minOriginal, _maxOriginal); }
getWidth()
Obtiene el ancho de una imagen en pixeles.
load($filename)
Carga una imagen.
output($imageType = IMAGETYPE_JPEG)
Imprime una imagen.
resize($width, $height)
Redimensiona una imagen por el ancho y alto.
resizeToHeight($height)
Redimensiona una imagen por el alto.
resizeToWidth($width)
Redimensiona una imagen por el ancho.
scale($scale)
Escala una imagen en porcentaje.
Clase Load
zan/classes/load.php
Esta clase permite cargar modelos, vistas, controladores, clases, libreras, ayudantes as como interactuar con plantillas.
Contenido
1 Cargando esta clase 2 Atributos 3 __construct() 4 app($application) 5 classes($class = NULL, $application = NULL) 6 config($name) 7 controller($controller, $application = NULL) 8 core($core) 9 CSS($CSS = NULL, $application = NULL, $print = FALSE) 10 driver($driver = NULL, $type = "db") 11 exception($exception) 12 execute($Class, $method, $params = array(), $type = "controller") 13 footer() 14 header() 15 helper($helper, $application = NULL) 16 hook($helper, $application = NULL) 17 js($script, $application = NULL, $extra = NULL, $getJS = FALSE) 18 language($language) 19 left() 20 library($name, $library = NULL) 21 model($name) 22 render() 23 right() 24 templates($name, $vars = NULL) 25 theme($theme) 26 title($title = NULL)
Atributos
@var private $application = FALSE @var public $Templates @var private $views = array()
__construct()
Carga los helpers autoload, router y validations, adems de los archivos de configuracin: cache, exceptions y languages.
app($application)
Inicializa el atributo $this->application con el nombre de la aplicacin que se este utilizando.
//This statement loads /applications/my_app/classes/my_class.php //The class must be within the "classes" directory inside the specific application directory $this->classes("my_class", "my_app");
config($name)
Carga un archivo de configuracin.
core($core)
//Loads "templates.php" from the core directory: zan/classes/ directory $this->Templates = $this->core("Templates");
//This statement loads a CSS file from a specific application directory //Loads applications/my_application/my_css_file.css $this->CSS("my_css_file", "my_application"); //This statement loads a CSS file from the main CSS directory //Loads www/lib/css/slides.css $this->CSS("slides");
header()
Carga una plantilla de encabezado.
//Loads "helper.my_helper.php" from the core directory: core/helpers directory $this->helper("my_helper"); //Loads "helper.my_helper.php" from a specific application directory: applications/my_application/helpers directory $this->helper("my_helper", "my_application");
//They can be loaded many helpers using an array of helpers $helpers = array("my_helper", "other_helper"); $this->helper($helpers);
//Loads "hook.my_hook.php" from the core directory: core/hooks directory $this->hook("my_hook"); //Loads "hook.my_hook.php" from a specific application directory: applications/my_application/hooks directory $this->hook("my_hook", "my_application"); //They can be loaded many hooks using an array of hooks $hooks = array("my_hook", "other_hook"); $this->hook($hooks);
$this->js("my_script", "my_app");
language($language)
Carga un archivo de lenguaje y configura las traducciones.
$this->language("Spanish");
left()
Carga la platilla izquierda.
$this->library("My_Lib_File", "My_Lib");
model($name)
Carga un Modelo.
render()
right()
Carga la plantilla derecha.
theme($theme)
Configura un tema. Funciona como Interfaz del mtodo theme de la clase Templates.
title($title = NULL)
Configura el ttulo del documento. Funciona como Interfaz del mtodo title de la clase Templates.
Clase Pagination
zan/classes/pagination.php
$this->Pagination = $this->core("Pagination");
__construct()
Carga el helper de HTML.
$this->Pagination = $this->core("Pagination"); $start = 0; $URL = _webBase . _sh . _webLang . _sh . _blog . _sh . _page . _sh; if($count > 10) { //Generates URLs like: http://www.mydomain.com/en/blog/page/2 $this->pagination = $this->Pagination->paginate($count, 10, $start, $URL); } else { $this->pagination = NULL; }
Clase Singleton
zan/classes/singleton.php
Esta clase implementa el patrn de diseo Singleton para PHP5, para evitar la clonacin de objetos.
Contenido
$this->Singleton = $this->core("Singleton");
Atributos
@var private static $instances = array();
__construct()
Vaco.
instance($class)
Evita la clonacin de objetos o de la clase recreacin de instancias. Si ya existe el objeto simplemente lo retorna, si no lo crea y lo retorna.
Clase Templates
zan/classes/templates.php
1 Cargando esta clase 2 Atributos 3 __construct() 4 CSS($CSS = NULL, $application = NULL, $print = FALSE) 5 exists($template, $view = FALSE) 6 getCSS() 7 getJs() 8 getThemes($theme) 9 getTitle() 10 isTheme() 11 js($js, $application = NULL, $extra = NULL, $getJs = FALSE) 12 load($template, $direct = FALSE) 13 theme($theme) 14 themeCSS($theme = _webTheme) 15 title($title = NULL) 16 vars($vars)
$this->Templates = $this->core("Templates");
Atributos
@var @var @var @var @var @var public $CSS public $js = NULL private $theme = NULL public $themePath public $title public $vars = array()
__construct()
Carga los ayudantes: array, browser, debbuging, form, html and web.
CSS($CSS = NULL, $application = NULL, $print = FALSE) exists($template, $view = FALSE) getCSS() getJs() getThemes($theme) getTitle() isTheme() js($js, $application = NULL, $extra = NULL, $getJs = FALSE) load($template, $direct = FALSE) theme($theme) themeCSS($theme = _webTheme) title($title = NULL) vars($vars)
Ayudante Alerts
core/helpers/alerts.php
Esta funcin contiene los errores y confirmaciones configurados por defecto en el Framework.
$this->helper("alerts");
Las siguientes funciones estn disponibles:
print getAlert("Success!", "Success" "http://mydomain.com/success"); //Prints: <a rev="External" href="mydomain.com/success">Success!</a> . //Note: The Alert type "Success", unsets $_POST by default.
Ayudante Array
core/helpers/array.php
$this->helper("array");
Las siguientes funciones estn disponibles:
isMultiArray($multiArray)
Retorna: @boolean; Retorna verdadero si el arreglo es una matriz, falso si solo es un simple vector. Ejemplo:
$array = array(1, 2, 3); //Returns false. if(isMultiArray($array)) { print "Returns true"; } else { print "Returns false"; } $array = array(1 => array(1, 2, 3)); //Returns true. if(isMultiArray($array)) { print "Returns true"; } else { print "Returns false"; }
Ayudante Benchmark
core/helpers/benchmark.php
El punto de referencia auxiliar permite realizar pruebas de evaluacin comparativa sobre las aplicaciones.
$this->helper("benchmark");
Las siguientes funciones estn disponibles:
benchMarkStart()
Retorna: @void; Esta funcin configura el tiempo Inicial del Punto de Referencia (BenchMark). Ejemplo:
benchMarkStart();
benchMarkEnd()
Retorna: @float; Esta funcin retorna el tiempo Final del Punto de Referencia (BenchMark). Ejemplo:
benchMarkStart(); $bar = 0; for($foo=1;$foo<=1000000;$foo++) { ++$bar; } usleep(1000000); //This function Delay execute time for 1sec = 1'000,000 microsec (1microsec = 0.000001 sec) print benchMarkEnd(); //Output a Float Value: 1.0910620689392. This value might vary.
Ayudante Browser
core/helpers/browser.php
$this->helper("browser");
Las siguientes funciones estn disponibles:
browser()
Retorna: String; Esta funcin retorna en forma de Cadena el Nombre del Navegador que es provista por el Agente de Usuario del mismo. Ejemplo:
browser(); //If the current User Agent is from a Chrome-based Browser. //Prints: "Chrome" .
Ayudante Debugging
core/helpers/debugging.php
$this->helper("debugging");
Las siguientes funciones estn disponibles:
___($text)
Retorna: vaco; Esta funcin es equivalente a la funcin die() de PHP. Ejemplo:
$array = array("One" => 1, "Two" => 2, "Three" => 3, "4"); ____($array); //This line of code will be truncated. print "ZanPHP v.1.0"; /* Returns.
array(4) { ["One"]=> int(1) ["Two"]=> int(2) ["Three"]=> int(3) [0]=> string(1) "4" } */
Si desea usar la funcin print_r() y no truncar el script, necesita cargar algunos parmetros extra. Ejemplo:
$array = array("One" => 1, "Two" => 2, "Three" => 3, "4"); ____($array, FALSE, FALSE); print "This is ZanPHP v.2.6 :)"; /* Returns. array(4) { ["One"]=> int(1) ["Two"]=> int(2) ["Three"]=> int(3) [0]=> string(1) "4" } This is ZanPHP v.2.6 :) */
Ayudante Forms
core/helpers/forms.php
The Helper Forms contains functions to manipulate HTML form elements with PHP.
Contenido
1 Cargando este Asistente 2 formCheckbox(array $attributes = FALSE) 3 formField($a = NULL, $text, $raquo = TRUE) 4 formInput(array $attributes) 5 formLabel(string $for, string $text, boolean $br = TRUE) 6 formRadio(array $attributes) 7 formSelect(array $attributes, array $options, bool $select = FALSE) 8 formTextarea(array $attributes, $value) 9 formOpen(array $attributes, string $legend) y formClose(array $attributes, string $legend)
$this->helper("forms");
Las siguientes funciones estn disponibles:
$attributes = array("id" => "Op1", "name" => "option1", "value" => "1", "type" => "checkbox", "onclick" => "alert('Option 1 selected');", "checked" => "checked", "text" => "Option 1"); print formCheckbox($attributes);
//Prints: "Option 1 <input id="Op1" name="option1" value="1" type="checkbox" onclick="alert('Option 1 selected');" checked="checked" /> " .
$attributes = array(); print formField(NULL, "Field Name", $raquo = TRUE); //Prints: <p class="Field"> Field Name </p> . //The parameter $raquo outputs the HTML Entity » if it is set up as TRUE.
Puede configurar un Ancla al Nombre del Campo. Ejemplo:
print field("Top", "Field Name", $raquo = TRUE); //Prints: <p class="Field"> <a name="Top"> Field Name </a> </p> .
formInput(array $attributes)
Retorna: @string; Esta funcin configura un etiqueta <input /> con atributos personalizados. Ejemplo:
$attributes = array("onclick" => "alert('My Alert')", "name" => "Bar", "value" = "Lorem", "class" => "Input", "type" => "text", "id" => "my_ID"); print formInput($attributes); //Prints: <input onclick="alert('My Alert')" name="Bar" value="Lorem" class="Input" type="text" id="my_ID" />
formRadio(array $attributes)
Retorna: @string; Esta funcin configura una etiqueta <input /> de tipo Radio y sus atributos. Ejemplo:
$attributes = array("text" => "Foo", "position" => "Right", "name" => "Bar", "value" => "1", "id" => "my-ID", "checked" => "checked"); print formRadio($attributes); //Prints: <input name="Bar" value="1" id="my-ID" title="foo" id="myID" checked="checked" /> Foo
$attributes = array("name" => "bar", "class" => "select", "id" => "foo"); $select = TRUE; // You can set <option> tags (for passing to $options parameter) this way: $options[0]["option"] = "Foo"; $options[0]["selected"] = TRUE; $options[0]["value"] = 1; //Here is another way: $options[1] = array("option" => "Bar", "selected" => FALSE, "value" => 2); print formSelect($attributes, $options, $select); //Prints: <select id="foo" name="bar" class="select"> <option value="1" selected="selected">Foo</option> <option value="2">Bar</option> </select>
$attributes = array("id" => "unique-id", "title" => "foo", "name" => "bar", "rows" => "25", "cols" => "90" "class" => "Textarea"); $value = "Default Text"; print formTextarea($attributes, $value); <textarea id="unique-id" title="foo" name="bar" rows="25" cols="90" class="Textarea"> Default Text </textarea>
$attributes = array("id" => "foo", "action" => "bar.php", "method" => "post", "class" => "forms", "enctype" => "multipart/form-data"); $legend = "Form"; print formOpen($attributes, $legend); //Your form elements here print formClose(); //Prints: <form id="foo" action="bar.php" method="post" class="forms" enctype="multipart/form-data"> <fieldset> <legend>Form</legend> //Your form elements here </fieldset> </form>
Ayudante HTML
core/helpers/forms.php
El Ayudante HTML contiene funciones para manipular elementos HTML mediante PHP.
Contenido
1 Cargando este Asistente 2 a(string $text, string $URL = NULL, bool $external = FALSE, array $attributes = array()) 3 body(boolean $open = TRUE) 4 bold(string $text, boolean $br) 5 br(integer $jumps = 1) 6 char(string $char, integer $repeat = 1) 7 div(string $ID, string $type = "id", string $style = NULL, string $content = NULL) 8 docType($type = "XHTML 1.0 Strict") 9 getHTMLDecode(string $HTML) 10 h1(string $text) 11 h2(string $text) 12 h3(string $text) 13 img(string $src, string $alt = NULL, string $class = "no-border", array $attributes = NULL) 14 head(boolean $open = TRUE) 15 HTML(boolean $open = TRUE) 16 p(string $text, string $class = "left") 17 small(string $text) 18 span(string $class = NULL, string $text, string $id = NULL) 19 openUl(string $ID = NULL, string $class = NULL) 20 li(string $list) 21 closeUl() 22 ul(string $list, string $ID = NULL, string $class = NULL)
$this->helper("html");
Las siguientes funciones estn disponibles:
a(string $text, string $URL = NULL, bool $external = FALSE, array $attributes = array())
Retorna: @string; Configura una etiqueta <a> y sus atributos. Ejemplo:
$text = "Link"; $URL = "http://www.example.com"; $attributes = array("id" => "foo", "class" => "bar"); ; print a($text, $URL, FALSE, $attributes); //Prints: <a href="http://www.example.com" id="foo" class="bar"> Link </a>
print body(TRUE); //Your HTML code here print body(FALSE); //Prints: <body> //Your HTML code here </body> //The parameter $raquo outputs the HTML Entity » if it is set up as TRUE.
$text = "Bolded text"; bold($text, TRUE); //Prints: <span class="bold"> Bolded text </span> <br /> //Note that $br parameter outputs an <br /> tag.
br(integer $jumps = 1)
Retorna: @string; Configura una etiqueta <br>. Ejemplo:
div(string $ID, string $type = "id", string $style = NULL, string $content = NULL)
Retorna: @string; Configura una etiqueta <div>. Ejemplo #1:
print div(FALSE); //Prints: //Note: If you set the $ID parameter as TRUE, a div tag is opened, but not closed <div id="foo"> //You HTML code here </div>
Ejemplo #2:
print div("foo", "id/class","bg_yellow"); //You HTML code here print div(FALSE); //Prints: //Note: If you set the $ID parameter as TRUE, a div tag is opened, but not closed <div id="foo" class="bg_yellow"> //You HTML code here </div>
Ejemplo #3:
print div("bg_yellow", "class"); //You HTML code here print div(FALSE); //Prints: //Note: If you set the $ID parameter as TRUE, a div tag is opened, but not closed <div class="bg_yellow"> //You HTML code here </div>
print docType(); //Prints: <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xHTML1/DTD/xHTML1-strict.dtd"> print docType("HTML 5"); //Prints: <!DOCTYPE html>
getHTMLDecode(string $HTML)
Retorna: @string; Convierte todas las entidades HTML de una cadena a sus caracteres correspondientes. Ejemplo:
$rawText = getHTMLDecode("I'll \"walk\" the <b>dog</b> now"); print $rawText; //Prints: I'll "walk" the <b>dog</b> now
h1(string $text)
Retorna: @string; Configura una etiqueta <h1>. Ejemplo:
h2(string $text)
Retorna: @string; Configura una etiqueta <h2>. Ejemplo:
h3(string $text)
Retorna: @string; Configura una etiqueta <h3>. Ejemplo:
img(string $src, string $alt = NULL, string $class = "no-border", array $attributes = NULL)
Retorna: @string; Configura una etiqueta <img />. Ejemplo:
$src = "http://www.example.com/foo.jpg"; $alt = "Lorem Ipsum"; print img($src, $alt, "no-border", NULL); //Prints: <img src="http://www.example.com/foo.jpg" alt="Lorem Ipsum" class="no-border" />
print head(TRUE); print "Foo"; print head(FALSE); //Prints: <head> Foo </head>
print HTML(TRUE); //Your HTML code here print head(FALSE); //Prints: <html xmlns="http://www.w3.org/1999/xhtml" lang="'._webLang.'" xml:lang="'._webLang.'"> //Your HTML code here </html>
small(string $text)
Retorna: @string; Configura una etiqueta <small>. Ejemplo:
$text = "Foo"; print span("yellow_bold", $text); //Prints: <span class="yellow_bold"> Foo </span>
Ejemplo #2:
$text = "Foo"; print span("yellow_bold", $text, "fooID"); //Prints: <span id="fooID" class="yellow_bold"> Foo </span>
$ID = "foo"; $class = "bar"; print openUl($ID, $class); //Prints: <ul id="foo" class="bar">
li(string $list)
Retorna: @string; Configura una etiqueta <li>. Ejemplo: Puede incluir un arreglo simple como parmetro y cargar uno o mltiples tems. Ejemplo:
$list[0] = "foo"; $list[1] = "bar"; $list[2] = "baz"; print openUl(); print li($list); print closeUl(); //Prints: <ul> <li> foo </li> <li> bar </li> <li> baz </li>
</ul>
Por otra parte, puede incluir mltiples elementos y sus atributos. Ejemplo:
$list[0]["item"] = "foo"; $list[0]["class"] = "lorem"; $list[1]["item"] = "bar"; $list[1]["class"] = "ipsum"; print openUl(); print li($list); print closeUl(); //Prints: <ul> <li class="lorem"> foo </li> <li class="ipsum"> bar </li> </ul>
closeUl()
Retorna: @string; Configura una etiqueta </li> de cierre. Ejemplo:
$list[0] = "foo"; $list[1] = "bar"; $list[2] = "baz"; print openUl(); print li($list); print closeUl(); //Prints: <ul> <li> foo </li> <li> bar </li> <li> baz </li> </ul>
$list[0]["item"] = "foo"; $list[0]["class"] = "bar"; $list[1]["item"] = "baz"; $list[1]["class"] = "ban"; $class = "lorem"; $id = "ipsum"; print ul($list, $ID, $class); //Prints: <ul> <li class="bar"> foo </li> <li class="ban"> baz </li> </ul>
Ayudante il8n
core/helpers/i18n.php
Contenido
1 Cargando este Asistente 2 __(string $text) 3 getXMLang(string $language, boolean $invert = FALSE) 4 whichLanguage(boolean $invert = FALSE) 5 isLanguage($language) 6 getLanguage($language)
$this->helper("i18n");
Las siguientes funciones estn disponibles:
__(string $text)
Retorna: @string; Esta funcin retorna la traduccin de un texto especfico. Ejemplo:
print __("Translated Text"); //It must exist a language translation document on core/language/ //In this case, all translations are returned by the translation() function at core/languages/language.spanish.php //Prints: "Texto Traducido" .
isLanguage($language)
Retorna: @string; Esta funcin define si una palabra es una Abreviatura XML estndar de un Lenguaje. Ejemplo:
getLanguage($language)
Retorna: @string; Esta funcin retorna la traduccin de la palabra que representa un lenguaje. Ejemplo:
print getLanguage("Spanish"); //Returns: "Espaol" . //The result depends on the default Language
Ayudante Inflect
core/helpers/inflect.php
$this->helper("inflect");
Las siguientes funciones estn disponibles:
pluralize(string $word)
Retorna: @string; Esta funcin retorna la forma plural de una palabra. Ejemplo:
singularize(string $word)
Retorna: @string; Esta funcin retorna la forma singular de una palabra. Ejemplo:
Ayudante Router
core/helpers/router.php
Contenido
$this->helper("router");
Las siguientes funciones estn disponibles:
execute()
Retorna: @void; Ejecuta el mtodo run() contenido en el controlador de cada una de las aplicaciones. Ejemplo:
segment(int $segment)
Retorna: @mixed; Esta funcin retorna una cadena con un segmento de URL especfico provista por el mtodo route(). Ejemplo:
print segment(0); //Prints: "en" //In this case the default value for segment(0) is a XML Language Abbreviation.
route()
Retorna: @mixed; Esta funcin retorna un Vector provisto por $_SERVER["REQUEST_URI"] separando cada posicin con una diagonal. Ejemplo:
var_dump(route()); //Prints: array(2) { [0]=> string(2) "en" [1]=> string(7) "myapp" } //The current URL: http://localhost/zanphp/index.php/en/myapp
getURL()
Retorna: @string; Esta funcin retorna una URL. Ejemplo:
Ayudante Security
core/helpers/security.php
Contenido
1 Cargando este Asistente 2 code(int $max, boolen $uppercase = TRUE) 3 escape(int $segment) 4 encripting(string $password = NULL, int $strong = 3, bool $key = TRUE, bool $uppercase = FALSE) 5 getIP() 6 ping() 7 redirect(string $URL, mixed $time = FALSE)
$this->helper("security");
Las siguientes funciones estn disponibles:
escape(int $segment)
Retorna: @mixed; Esta funcin retorna escapa fragmentos de cadena potencialmente peligrosas dentro de una cadena para evitar, por ejemplo, inyecciones SQL. Ejemplo:
$string = "'OR'1'='1"; print escape($string); //Prints: "1=1" //This is a common SQL Injection.
encrypt(string $password = NULL, int $strong = 3, bool $key = TRUE, bool $uppercase = FALSE)
Retorna: @mixed; Esta funcin retorna una cadena encriptada. Ejemplo:
$pass = "my_pass"; print encripting($pass, 1, TRUE, TRUE); //Prints: "0F9B54A15E8FE458B2E1ED77DE7CC84F" //If $key parameter is set as TRUE, the returned string is encripted using a timestamp, //in the other hand, if set as FALSE, it is encripted with a default external key.
Puede definir la fuerza del cifrado. Ejemplo:
$pass = "my_pass"; print encripting($pass, 3, TRUE, TRUE); //Prints: "8274FE3BC002381FD8698795929B05B1AC412CA3" //There is three encripting levels.
getIP()
Retorna: @mixed; Esta funcin retorna la direccin IP del Usuario. Ejemplo:
ping()
Retorna: @string; Esta funcin enva un ping a una URL. Ejemplo:
redirect("www.mydomain.com", 1);
Ayudante Sessions
core/helpers/sessions.php
Contenido
1 Cargando este Asistente 2 unsetCookie(string $cookie, string $URL = _webBase) 3 unsetSession(string $URL = _webBase) 4 createCookie(string $cookie, string $value, bool $redirect = FALSE, string $URL = _webBase, int $time = 604800) 5 createSession(string $session = NULL, string $value = NULL, bool $redirect = FALSE, string $URL = _webBase) 6 SESSION(string $session)
$this->helper("sessions");
Las siguientes funciones estn disponibles:
$URL = "www.mydomain.com" unsetCookie("foo", $URL); //Unset the $_COOKIE["foo"] and redirects to www.mydomain.com //It must be include the Security helper
$URL = "www.mydomain.com" unsetSessions($URL); //Unset all session variables and redirects to www.mydomain.com //It must be include the Security helper
createCookie(string $cookie, string $value, bool $redirect = FALSE, string $URL = _webBase, int $time = 604800)
Retorna: @mixed; Esta funcin crea una Cookie. Ejemplo:
createCookie("my_cookie", "foo", TRUE, "www.mydomain.com", 3600); //Creates cookie: "my_cookie", with the string value: "foo", redirects to www.mydomain.com and set the live of the cookie in 1 hour //It must be include the Security helper
createSession(string $session = NULL, string $value = NULL, bool $redirect = FALSE, string $URL = _webBase)
Retorna: @mixed; Esta funcin crea una variable de sesin. Ejemplo:
createSession("foo", "bar", TRUE, "www.mydomain.com"); //Sets variable session: "foo", with the string value: "bar" and redirects to www.mydomain.com //It must be include the Security helper
SESSION(string $session)
Retorna: @mixed; Esta funcin devuelve el valor de una variable de sesin. Ejemplo:
$_SESSION["foo"] = "bar"; //Assuming "foo" is a $_SESSION variable and it is set. SESSION("foo"); //output: "bar"
Ayudante String
core/helpers/string.php
Contenido
1 Cargando este Asistente 2 cleanHTML(string $HTML) 3 removeSpaces(string $text, bool $trim = FALSE) 4 compress(string $string) 5 POST(string $position, string $coding = "decode"), GET(string $position, string $coding = "decode") 6 FILES(string $name = FALSE, string $position = NULL) 7 recoverPOST(string $position, string $value = NULL) 8 getFileSize(int $size) 9 filter(string $text, boolean $cleanHTML = FALSE) 10 encode(string $text, bool $URL = FALSE) 11 decode(string $text, bool $URL = FALSE)
$this->helper("string");
Las siguientes funciones estn disponibles:
cleanHTML(string $HTML)
Retorna: @void; Esta funcin limpia el HTML contenido en una cadena. Ejemplo:
ipsum"; ipsum";
compress(string $string)
Retorna: @string; Esta funcin comprime una cadena. Ejemplo:
$HTML = " <html> <head> <title>Foo</title> </head> <body> <p> <a href='#'> bar </a> </p> </body> </html> "; print $HTML; //Prints: <html> <head> <title>Foo</title> </head> <body> <p> <a href='#'> bar </a> </p> </body> </html> print compress($HTML);
//Prints: <html> <head> <title>Foo</title> </head> <body> <p> <a href='#'> bar </a> </p> </body> </html>
POST(string $position, string $coding = "decode"), GET(string $position, string $coding = "decode")
Retorna: @mixed; Esta funcin obtiene datos de $_POST o $_GET. Ejemplo:
if(POST("foo") !== FALSE) print POST("foo", "encode"); //Prints: "bar" //Assuming the user Posted foo = bar ($_POST["foo"] = "bar") if(GET("lorem") !== FALSE) print GET("lorem", "encode"); //Prints: "ipsum" //Assuming the user entered http://example.com/?lorem=ipsum
FILES("download", "name"); //Assuming "image" is set and it is a file. Array { [name] => MyFile.jpg }
recoverPOST("foo"); //Prints: "bar" //Assuming the user Posted foo = bar ($_POST["foo"] = "bar")
recoverPOST("foo", "lorem");
getFileSize(int $size)
Retorna: @string; Esta funcin facilita el trabajo con datos numricos. Ejemplo:
== nice(string $title) == '''Retorna:''' @string; Esta funcin retorna la forma -nice- (agradable) de una cadena. Ejemplo: <source lang="php"> $text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit"; print nice($text); //Prints: "lorem-ipsum-dolor-sit-amet-consectetur-adipiscingelit"
Ayudante Time
zan/helpers/time.php
1 Cargando este Asistente 2 getHour($date) 3 getSeconds($time) 4 getTime($date) 5 howLong($value) 6 isLeapYear($year) 7 isDay($day) 8 isMonth($month) 9 isYear($year) 10 month($month) 11 now($format, $hour = FALSE, $language = NULL)
$this->helper("alerts");
getHour($date) getSeconds($time) getTime($date) howLong($value) isLeapYear($year) isDay($day) isMonth($month) isYear($year) month($month) now($format, $hour = FALSE, $language = NULL)
Ayudante Validations
core/helpers/validations.php
Contenido
1 Cargando este Asistente 2 isEmail(string $email) 3 isInjection(string $text, integer $count) 4 isSPAM(string $content, integer $count = 2) 5 isVulgar(string $content, integer $count = 1)
$this->helper("validations");
Las siguientes funciones estn disponibles:
isEmail(string $email)
Retorna: @boolean; Valida si una cadena es un email. Ejemplo:
$goodMailString = "foo@example.com"; $badMailString = "#$%&/.com@" isEmail($goodMailString); #Returns TRUE isEmail($badMailString); #Returns FALSE
$content = "get the fuck off bitch"; isVulgar($content, 1); #Returns TRUE