• Acasă
  • Despre noi
  • Autori
  • Mărturii
  • Arhivă
  • Trimite Articol
  • Contact

WORLDIT

Lumea în 1 și 0.

  • Știri
    • Tehnologie
    • Tehnologie mobilă
    • Securitate
    • Developers
    • Știință
    • Benzi desenate
    • Jocuri
    • Intern
  • Tehnic
    • Browser
    • C#
    • C/C++
    • Challenge
    • HTML/CSS
    • Javascript, Ajax, jQuery
    • Open Source
    • PHP
    • Python
    • Securitate IT
    • Socializare
    • WordPress
    • Altele
  • Recenzii
  • Interviuri
  • Evenimente

Introducere in Design Patterns – MVC (partea aII-a)

1
  • Publicat de Andrei Avădănei
  • în Fără categorie
  • — 24 mai, 2010 at 8:00 am

In urma cu cateva zile am introdus cateva din notiunile de baza ale programarii orientate pe obiecte, folosind sabloane de lucru (design patterns). Prima parte a reprezentat o introducere in MVC, urmand ca actualul articol sa acopere cateva lucruri mai tehnice, ce fac referire la obiectele de baza ale unui framework in format MVC.

Fisierul de configurare – config/config.php

Despre acesta nu sunt prea multe de spus. Aici vom seta conexiunea la baza de date, respectiv starea mediului (in dezvoltare sau produs final).

<?php
/** Configuration Variables **/


define('DB_NAME', 'database');
define('DB_USER', 'username');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');

Configure::write('Dev.Enviroment', TRUE);

?>

Modulul de Cache – library/cache.php

Acest modul va reprezenta un aspect foarte important in cazul in care veti fi nevoiti sa creati aplicatii ce se asteapta la un trafic mare. Fisierul library/cache.php contine clasa CacheEngine(), o clasa aproape abstracta ce va reprezenta sablonul oricarei metode de cache-ing si clasa Cache(), extindere de la Object(). Cea din urma reprezinta clasa ce detine o serie de functii statice, ce pot fi apelate din interiorul frameworkului, creand si dirijand informatiile necesare unui obiect copil ce este o extindere a clasei CacheEngine().

Clasa Cache()

Deoarece clasa este mult prea mare pentru a putea fi prezentata aici, voi include doar antetele functiilor, alaturi de parametrii formali alaturi de explicatiile aferente.

class Cache extends Object
{
	private $settings = array();
	private $name = 'default';
	private $CacheEngine = NULL;
	private $reset = FALSE;
	private $_config = array();
	
	/**
	 * Returns a singleton instance of Cache Class
	 *
	 * @return object
	 * @access public
	 * @static
	 **/
	public static function &getInstance() ;
	
	/**
	 * Tries to find and include a file for a cache engine and returns object instance
	 *
	 * @param $name	Name of the engine [without 'Engine']
	 * @return mixed $engine object or null
	 * @access private
	 **/
	private function _loadEngine($name);
	
	/**
	 * Write data for key into cache
	 *
	 * @param string $key Identifier for the data
	 * @param mixed $value Data to be cached - anything except a resource	 
	 * @return boolean True if the data was successfully cached, false on failure
	 * @access public
	 * @static
	 **/
	public static function write($key = NULL, $value = NULL, $name = NULL);
	
	/**
	 * Read a key from the cache
	 *
	 * @param string $key Identifier for the data
	 * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
	 * @access public
	 * @static
	 **/
	public static function read($key, $name = NULL);
	
	/**
	 * Delete a key from the cache
	 *
	 * @param string $key Identifier for the data
	 * @return boolean True if the value was succesfully deleted, false if it didn't exist or couldn't be removed
	 * @access public
	 * @static
	 **/
	public static function delete($key, $name = NULL);
	
	/**
	 * Delete all keys from the cache
	 *
	 * @param boolean $check if true will check expiration, otherwise delete all
	 * @return boolean True if the cache was succesfully cleared, false otherwise
	 * @access public
	 * @static
	 **/
	public static function clear($check, $name = NULL);
	
	/**
	 * Garbage collection
	 *
	 * Permanently remove all expired and deleted data
	 *
	 * @return void
	 * @access public
	 * @static
	 **/
	public static function gc();
	
	/**
	 * Check if Cache has initialized a working storage engine
	 *
	 * @param string $engine Name of the engine
	 * @param string $config Name of the configuration setting
	 * @return bool
	 * @access public
	 * @static
	 **/
	public static function isInitialized($engine = NULL);
	
		
	/**
	 * Get and sets the cache configuration
	 *
	 * @access public
	 * @static
	 **/
	public static function initConfig($name, $settings = array());
	
	/**
	 * Init engine settings (a specific $name engine)
	 *
	 * @param string $name Name of the engine 
	 * @param array $settings Settings passed to the engine
	 * @return boolean True on success, false on failure
	 * @access public
	 * @static
	 **/
	public static function initEngine($name = 'File', $settings = array());
	
	/**
	 * Change settings to current config temporary. if no params are passed, resets settings
	 *
	 * @param mixed $settings Optional string for simple name-value pair or array
	 * @param string $value Optional for a simple name-value pair
	 * @return array of settings
	 * @access public
	 * @static
	 **/
	public static function set($settings = array(), $value = NULL);
	
	/**
	 * Settings for current cache engine
	 *
	 * @param string $engine Name of the engine
	 * @return array list of settings
	 * @access public
	 * @static
	 **/
	public static function getSettings($engine = null);
}
?>

Clasa CacheEngine()

class CacheEngine
{
	public $settings = array();
	
	/**
	 * Initialize the cache engine
	 *
	 * Called automatically by the cache frontend
	 *
	 * @param array $params Associative array of parameters for the engine
	 * @return boolean True if the engine has been succesfully initialized, false if not
	 * @access public
	 **/
	public function init($settings = array())
	{
		$this->settings = array_merge(array('prefix' => 'cache_', 
										   'duration'=> 3600
										   ),
									 $settings
									 );
		 
		if (!is_numeric($this->settings['duration'])) 
			$this->settings['duration'] = strtotime($this->settings['duration']) - time();
		return true;
	}
	
	/**
	 * Garbage collection
	 *
	 * Permanently remove all expired and deleted data
	 *
	 * @access public
	 **/
	public function gc() 
	{
		
	}
	
	/**
	 * Write value for a key into cache
	 *
	 * @param string $key Identifier for the data
	 * @param mixed $value Data to be cached
	 * @param mixed $duration How long to cache the data, in seconds
	 * @return boolean True if the data was succesfully cached, false on failure
	 * @access public
	 **/
	function write($key, &$value, $duration)
	{
		trigger_error(sprintf(__('Method write() not implemented in %s', true), get_class($this)), E_USER_ERROR);
	}
	
	/**
	 * Read a key from the cache
	 *
	 * @param string $key Identifier for the data
	 * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
	 * @access public
	 **/
	function read($key) 
	{
		trigger_error(sprintf(__('Method read() not implemented in %s', true), get_class($this)), E_USER_ERROR);
	}
	
	/**
	 * Delete a key from the cache
	 *
	 * @param string $key Identifier for the data
	 * @return boolean True if the value was succesfully deleted, false if it didn't exist or couldn't be removed
	 * @access public
	 **/
	function delete($key)
	{
		trigger_error(sprintf(__('Method delete() not implemented in %s', true), get_class($this)), E_USER_ERROR);
	}
	
	/**
	 * Delete all keys from the cache
	 *
	 * @param boolean $check if true will check expiration, otherwise delete all
	 * @return boolean True if the cache was succesfully cleared, false otherwise
	 * @access public
	 **/
	function clear($check) 
	{
		trigger_error(sprintf(__('Method clear() not implemented in %s', true), get_class($this)), E_USER_ERROR);
	}
	
	/**
	 * Cache Engine settings
	 *
	 * @return array settings
	 * @access public
	 **/
	function getSettings() 
	{
		return $this->settings;
	}
	
	/**
	 * Make the key safe
	 *
	 * @param string $key the key passed over
	 * @return mixed string $key or false
	 * @access public
	 **/
	function key($key)
	{
		if (empty($key)) 
			return FALSE;
		
		$key = str_replace(array(DS, '/', '.'), '_', strval($key));
		return $key;
	}
}

Mai avem nevoie de fisierul config/core.php, in care vom instatia setarile de baza ale clasei default de cache: FileEngine.

<?php

 /**
 *
 * Cache Engine Configuration
 * Default settings provided below
 *
 * File storage engine.
 *
 **/
 Cache::initConfig('default', array(
									'engine'    => 'File',   //[required]
									'duration'  => 3600,     //[optional]
									'path'      => CACHE,    //[optional] use system tmp directory - remember to use absolute path
									'prefix'    => 'cache_', //[optional]  prefix every cache file with this string
									'lock'      => false,    //[optional]  use file locking
									'serialize' => true		 //[optional]
									)	 
				   );  
 
 Configure::write('Cache.disabled', FALSE);
 
?>

Clasa FileEngine, fisierul library/cache/file.php

Directorul library/cache va contine toate modulele (sistemele) de cache care doriti sa le includeti in framework. Am creat ca exemplu libraria FileEngine, ce detine toate functiile clasei CacheEngine deoarece reprezinta extensia acesteia. Nu are rost sa incarc pagina si mai mult decat este, codul sursa il veti avea complet la sfarsitul articolului.

Clasele pentru manipularea fisierelor si a directoarelor

Aceste doua clase sunt necesare, deoarece sunt folosite din plin la FileEngine(). Clasa File, extindere de la Object, implementeaza aproape toate functiile de manipulare ale fisierelor. Mai jos aveti antetele functiilor puse la dispozitie, alaturi de explicatiile aferente.

class File extends Object
{
	public $Folder = NULL;
	public $name = NULL;
	public $handler = NULL;
	public $lock = FALSE;
	public $path = NULL;
	
	public function __construct($path = NULL, $create = FALSE, $chmode = 0755);
	
	/**
	 * Closes the current file if it is opened
	 *
	 * @access public
	 */
	public function __destruct();
	
	/**
	 * Opens the current file with a given $mode
	 *
	 * @param string $mode A valid 'fopen' mode string : r, w, a, etc.
	 * @param boolean $force force the file to open
	 * @return boolean True on success, false on failure
	 * @access public
	 */
	public function open($mode = 'w', $force = FALSE);
	
	/**
	 * Creates the File.
	 *
	 * @return boolean Success
	 * @access public
	 */
	public function create();
	
	/**
	 * Return the contents of this File as a string.
	 *
	 * @param string $bytes how many bytes to read
	 * @param string $mode (r | rb etc)
	 * @param boolean $force force the file to open
	 * @return mixed string on success, false otherwise
	 * @access public
	 */
	public function read($bytes = FALSE, $mode = 'r', $force = FALSE);
	
	/**
	 * Write content data to this File.
	 *
	 * @param string $data	Data to write to this File.
	 * @param string $mode	Mode of writing. Examples : w, w+ etc
	 * @param string $force	force the file to open
	 * @return boolean Success
	 * @access public
	 */
	public function write($data, $mode = 'w', $force = FALSE);
	
	/**
	 * Append data to File.
	 *
	 * @param string $data Data to write
	 * @param string $force	force the file to open
	 * @return boolean Success
	 * @access public
	 */
	public function append($data, $force = FALSE);
	
	/**
	 * Deletes the File.
	 *
	 * @return boolean Success
	 * @access public
	 */
	public function delete();
	
	/**
	 * Check if file exists.
	 *
	 * @return boolean true if it exists, false otherwise
	 * @access public
	 */
	public function exists();
	
	
	/**
	 * Get md5 Checksum of File
	 *
	 * @return string md5 Checksum
	 * @access public
	 */
	public function md5();
	
	/**
	 * Get sha1 Checksum of File
	 *
	 * @return string md5 Checksum
	 * @access public
	 */
	public function sha1();
	
	/**
	 * Returns the File extension.
	 *
	 * @return string The File extension
	 * @access public
	 */
	public function ext();
	
	/**
	 * Returns and sets the full path of the File.
	 *
	 * @return string Full path to file
	 * @access public
	 */
	public function pwd();
	
	/**
	 * Returns File name, without extension.
	 *
	 * @return string File name, without extension.
	 * @access public
	 */
	public function name();
	
	/**
	 * Closes the current file.
	 *
	 * @return boolean True if successfully closed, otherwise false
	 * @access public
	 */
	public function close();
	
	/**
	 * Returns File chmod.
	 *
	 * @return string chmod for the file, false otherwise
	 * @access public
	 */
	public function perms();
	
	/**
	 * Get Filesize
	 *
	 * @return integer size of the file in bytes, false otherwise
	 * @access public
	 */
	public function size();
    
	/**
	 * Check if File is readable.
	 *
	 * @return boolean true if file is readable, false otherwise
	 * @access public
	 */
	function readable() ;
	
	/**
	 * Check if File is writable.
	 *
	 * @return boolean true if its writable, false otherwise
	 * @access public
	 */
	function writable() ;
	
	/**
	 * Check if File is executable.
	 *
	 * @return boolean true if its executable, false otherwise
	 * @access public
	 */
	function executable() ;
	
	/**
	 * Returns the File's owner.
	 *
	 * @return integer the Fileowner
	 * @access public
	 */
	public function owner();
	
	/**
	 * Returns the File group.
	 *
	 * @return integer the Filegroup
	 * @access public
	 */
	public function group();
	
	/**
	 * Returns last access time.
	 *
	 * @return integer timestamp Timestamp of last access time
	 * @access public
	 */
	public function lastAccess();
    
	/**
	 * Get last modified time.
	 *
	 * @return integer timestamp Timestamp of last modification, false otherwise
	 * @access public
	 */
	public function lastChange();
	
	/**
	 * Returns the File basedir handler.
	 *
	 * @return Folder Current folder
	 * @access public
	 */
	public function &Folder();
}

Clasa Folder, extindere la Object, este o clasa ce ajuta la manipularea directoarelor intregi. Din pacate aceasta clasa prezinta doar cateva functii de baza. Daca doriti sa contribuiti la ea, nu ezitati sa dati un comentariu aici. Mai jos aveti antetele functiilor din aceasta clasa alaturi de explicatii aferente.

class Folder extends Object
{ 
	private $path = NULL;
	private $mode = FALSE;
	
	public function __construct($path = NULL, $create = FALSE, $mode = FALSE);
	
	/**
	 * Returns true if given $path is an absolute path.
	 *
	 * @param string $path Path to check
	 * @return bool
	 * @access public
	 * @static
	 */
	public static function isAbsolute($path) ;
	
	/**
	 * Returns true if given $path is a Windows path.
	 *
	 * @param string $path Path to check
	 * @return boolean true if windows path, false otherwise
	 * @access public
	 * @static
	 */
	 public static function isWindowsPath($path);
	
	
	/**
	 * Change directory to $path.
	 *
	 * @param string $path Path to the directory to change to
	 * @return string The new path, fale otherwise
	 * @access public
	 */
	public function cd($path);
	
	/**
	 * Return current path.
	 *
	 * @return string Current path
	 * @access public
	 */
	public function pwd();
	
	public function realpath($path);
	
	/**
	 * Returns true if the File is in given path.
	 *
	 * @return bool
	 * @access public
	 */
	public function inPath($path = '', $reverse = FALSE);
	
	
	/**
	 * Returns a correct set of slashes for given $path. (\\ for Windows paths and / for other paths.)
	 *
	 * @param string $path Path to check
	 * @return string Set of slashes ("\\" or "/")
	 * @access public
	 * @static
	 */
	 public static function correctSlashFor($path);
	
	/**
	 * Returns $path with added terminating slash (corrected for Windows or other OS).
	 *
	 * @param string $path Path to check
	 * @return string Path with ending slash
	 * @access public
	 * @static
	 */
	public static function slashTerm($path);
	
	/**
	 * Returns true if given $path ends in a slash (i.e. is slash-terminated).
	 *
	 * @param string $path Path to check
	 * @return boolean true if path ends with slash, false otherwise
	 * @access public
	 * @static
	 */
	public static function isSlashTerm($path) ;
}

Clasa XMLParser

Clasa aceasta reprezinta modificarea si compatibilizarea cu frameworkul al unei clase XML despre care am discutat in urma cu ceva vreme cand am invatat cum putem parsa fisierele XML in obiecte. Clasa a suferit mici modificari tehnice, dar explicatiile/functiile si modul de functionare al acestora il puteti gasi in stare intacta aici.

Concluzie

Aceasta parte a articolului nu a vizat prea mult modelul MVC, fiind doar o pregatire a ceea ce urmeaza. Am dorit sa nu incarc prea mult articolul cu informatie, pentru ca astfel va putea fi digerata mai usor pana la urmatoarea si ultima parte. Respectiva va contina la propriu exemplificarea si punerea cap la cap a a tuturor chestiilor invatate, dovedind ca ce am comentat eu aici nu a fost doar pentru a adauga inca un articol la contor. Tot acolo vom explica mai pe larg conceptele Model, View si Controller. Enjoy. 🙂

Etichete: ce este mvcclasedesign patternsdespre factorydespre mvcdespre rgistrydespre singletonintroducere in mvcmodel view controllermvcoopPHPpooTehnictutorial design patternstutorial mvc

— Andrei Avădănei a scris 1246 articole

Andrei scrie pe worldit.info din vara lui 2011. Este fondatorul Asociatiei Centrul de Cercetare in Securitate Informatica din Romania - CCSIR si coordoneaza DefCamp, cea mai importanta conferinta de securitate informatica & hacking din Europa Centrala si de Est. Andrei ofera in cadrul Bit Sentinel servicii de securitate informatica, penetration testing, security management, recuperarea de pe urma unui atac cibernetic, training-uri si workshop-uri.

  • Articolul anterior Cum sa verifici timpul de incarcare ale website-ului tau?
  • Articolul următor Google Pac-Man are pagina oficiala

1 Comentariu

  1. Cornescu Andrey spune:
    mai 24, 2010 la 3:49 pm

    Super imi place 😀


  • Facebook

    WorldIT.info
  • Ultimele Atacuri Cibernetice din Romania – RO Hacked

    [wp_rss_retriever url="https://rohacked.bit-sentinel.com/feed/" excerpt="none" items="5" read_more="false" new_window="true" thumbnail="false" cache="0"] RO Hacked este registrul atacurilor cibernetice din România.
  • Caută

  • Articole Recomandate

    • Recent Posts
    • Tags
    • Număr record de participanți la DefCamp 2015, cel mai important eveniment dedicat securității cibernetice din Europe Centrala si de Estdecembrie 2, 2015
    • La DefCamp 2015 vei afla prin ce tehnici pot fi evitate măsurile de securitate ale sistemelor informatice criticeoctombrie 16, 2015
    • Ultima sansa sa rezervi bilete de tip Early Bird la DefCamp 2015septembrie 1, 2015
    • 15 sfaturi despre cum poti deveni un programator bun venite de la specialisti romaniaugust 4, 2015
    • algoritmica Android antivirus Apple Avadanei Andrei benzi desenate BitDefender blog browser C++ Chrome concurs eveniment Facebook Firefox Google google chrome hacking html5 infografic informatica internet Internet Explorer IT javascript linux Microsoft Mozilla Firefox online PHP programare retea sociala review Romania securitate Tehnologie Twitter web Windows Windows 7 Wordpress WorldIT worldit.info Yahoo! YouTube
  • august 2022
    L Ma Mi J V S D
    1234567
    891011121314
    15161718192021
    22232425262728
    293031  
    « dec.    
  • Link-uri Sponsorizate

    • laptop second hand

    • Calculatoare Second Hand

    • cod voucher pc garage

  • Home
  • Introducere in Design Patterns – MVC (partea aII-a)
  • Important

    • Bit Sentinel
    • Centrul de Cercetare în Securitate Informatică din România
    • DefCamp
  • Prieteni

    • BetiT.ro
    • bijuterii handmade
    • Computerica | Resurse gratuite PC
    • Descopera.org
    • Gadgeturi si IT – Giz.ro
  • Prieteni

    • PC – Config
    • RO Hacked
    • Stiri IT

Copyright © 2009-2014 WORLDIT. Toate drepturile Rezervate.
Termeni și condiții | Contact | Licența Creative Commons