<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Всякие интересные штучки для WEB-разработчика &#187; PHP</title>
	<atom:link href="http://iphp.com.ua/archives/category/php/feed" rel="self" type="application/rss+xml" />
	<link>http://iphp.com.ua</link>
	<description>блог о технологиях web-разработки // all your base are belong to us</description>
	<lastBuildDate>Thu, 24 Jun 2010 05:23:12 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Really Useful Classes And Libraries For PHP Developers</title>
		<link>http://iphp.com.ua/archives/514</link>
		<comments>http://iphp.com.ua/archives/514#comments</comments>
		<pubDate>Sat, 27 Feb 2010 00:36:48 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://iphp.com.ua/archives/514</guid>
		<description><![CDATA[Today millions of websites and servers across the Internet are powered by PHP. Originally created by Rasmus Lerdorf in 1995 so that anyone can easily create a Personal Home Page; PHP has come a long way and is now widely used as general purpose scripting language that is suitable for majority of web development projects. [...]]]></description>
			<content:encoded><![CDATA[<p>Today millions of websites and servers across the Internet are  powered by PHP. Originally created by <a href="http://en.wikipedia.org/wiki/Rasmus_Lerdorf" target="_blank">Rasmus  Lerdorf</a> in 1995 so that anyone can easily create a Personal Home  Page; PHP has come a long way and is now widely used as general purpose  scripting language that is suitable for majority of web development  projects.</p>
<p>Numerous <a href="http://www.phpframeworks.com/" target="_blank">PHP  Frameworks</a> have evolved to enable rapid web development with PHP.  However even greater number of standalone PHP libraries and classes are  available which provide similar benefits. W3Avenue has compiled a list  of some really useful classes and libraries that every PHP developers  should be familiar with. Whether you like to use a PHP Framework or  prefer to work without one, your productivity can multiply with the help  of these libraries and classes.</p>
<p><span id="more-514"></span></p>
<h3>Database</h3>
<ul>
<li><a href="http://adodb.sourceforge.net/" target="_blank"><strong>ADOdb</strong></a><br />
An object oriented library written in PHP that abstracts database  operations for portability. It is modeled on Microsoft’s <strong>ADO</strong>,  but has many improvements that make it unique (eg. <strong>Pivot Tables</strong>,  <strong>Active Record</strong> support, generating HTML for paging  recordsets with next and previous links, cached recordsets, HTML menu  generation, etc). Supports large number of databases including: MySQL,  PostgreSQL, Interbase, Firebird, Informix, Oracle, MS SQL, Foxpro,  Access, ADO, Sybase, FrontBase, DB2, SAP DB, SQLite, Netezza, LDAP, and  generic ODBC, ODBTP.</li>
<li><strong><a href="http://www.redbeanphp.com/" target="_blank">RedBean</a></strong><br />
RedBean is an easy, lightweight ORM for PHP that doesn’t require any  configuration and works out of the box. The only requirement is a  database connection string; it offer a single setup-class that gets you  up and running with just 1 single method invocation.</li>
<li><a href="http://www.doctrine-project.org/" target="_blank"><strong>Doctrine</strong></a><br />
Doctrine is an object relational mapper (<strong>ORM</strong>) for PHP  5.2.3+ that sits on top of a powerful database abstraction layer (DBAL).  One of its key features is the option to write database queries in a  proprietary object oriented SQL dialect called Doctrine Query Language  (DQL), inspired by Hibernates HQL. This provides developers with a  powerful alternative to SQL that maintains flexibility without requiring  unnecessary code duplication.</li>
<li><a href="http://phplinq.codeplex.com/" target="_blank"><strong>PHPLINQ</strong></a><br />
A set of PHP classes mimicing C#3.0’s <strong>LINQ</strong> (Language  Integrated Query) extension methods.PHPLinq currently features: LINQ  operators (select, take, skip, orderBy / orderByDescending, thenBy /  thenByDescending), Lambda expressions, and Anonymous types.</li>
<li><a href="http://mimesis.110mb.com/" target="_blank"><strong>Mimesis</strong></a><br />
Mimesis is an Open Source PHP <strong>Flat File Database</strong> low-level API designed to act as a backend for server-side scripts that  require database functionality. Instead of parsing SQL statements,  Mimesis uses PHP’s object-oriented constructs to provide a distinct  class with various database manipulation methods.</li>
</ul>
<h3>Development</h3>
<ul>
<li><a href="http://matrix.squiz.net/developer/tools/php_cs" target="_blank"><strong>PHP CodeSniffer</strong></a><br />
PHP CodeSniffer is a PHP5 script that tokenizes and “sniffs” PHP code to  detect violations of a defined set of coding standards. It is an  essential development tool that ensures that your code remains clean and  consistent. It can even help prevent some common semantic errors made  by developers.</li>
<li><a href="http://manual.phpdoc.org/" target="_blank"><strong>phpDocumentor</strong></a><br />
Similar to Javadoc, and written in php, phpDocumentor can be used from  the command line or a web interface to create professional <strong>documentation</strong> from php source code. phpDocumentor has support for linking between  documentation, incorporating user level documents like tutorials and  creation of highlighted source code with cross referencing to PHP  general documentation.</li>
</ul>
<h3>Document</h3>
<ul>
<li><a href="http://www.tcpdf.org/" target="_blank"><strong>TCPDF</strong></a><br />
An Open Source PHP class for generating <strong>PDF</strong> documents.  Requires no external libraries for the basic functions; supports all ISO  page formats including UTF-8, Unicode, RTL languages and HTML.</li>
<li><a href="http://www.phppowerpoint.net/" target="_blank"><strong>PHPPowerPoint</strong></a><br />
Based on Microsoft’s OpenXML standard PHPPowerPoint Classes enables you  to read and write <strong>PowerPoint</strong> files. Features include:  setting presentation meta data (author, title, description, …), adding  slides, adding images to your presentation and much more!</li>
<li><a href="http://www.phpexcel.net/" target="_blank"><strong>PHPExcel</strong></a><br />
Based on Microsoft’s OpenXML standard PHPExcel Class enables you to read  and write <strong>Excel</strong> files. Features include:  setting  spreadsheet meta data (author, title, description, …), multiple  worksheets, different fonts and font styles, cell borders, fills,  gradients, adding images to your spreadsheet and much, much more!</li>
<li><a href="http://sourceforge.net/projects/phprtf/" target="_blank"><strong>PhpRtf  Lite</strong></a><br />
Purpose of this library is to create <strong>RTF</strong> documents with  PHP, which are compatible with <strong>Microsoft Word</strong> and <strong>Open  Office Writer</strong> programs. Main features include: Document  sections formatting: margins, paper size, borders and other (document  can have more than one section); Headers and footer formatting;  Paragraph control: background, borders, alignment and other; Font  control: bold, italic, face, size, color (it’s possible to use html  style tags); Embedded images (.jpg and .png formats); Tables formatting:  sizes, borders, background and alignment of cells; UTF-8 support.</li>
<li><a href="http://www.phpconcept.net/pclzip/index.en.php" target="_blank"><strong>PclZip</strong></a><br />
Offers <strong>compression</strong> and <strong>extraction</strong> functions for <strong>Zip</strong> formatted archives (WinZip, PKZIP).  It gives you the ability to create an archive, list the content and  extract all its content in the file system. PclZip defines an object  class which represent a Zip Archive. This class manages the archive  properties and offers access method and actions on the archive.</li>
</ul>
<h3>Email</h3>
<ul>
<li><a href="http://swiftmailer.org/" target="_blank"><strong>Swift  Mailer</strong></a><br />
Swift Mailer integrates into any web app written in PHP 5, offering a  flexible and elegant object-oriented approach to sending emails with a  multitude of features: Send emails using <strong>SMTP</strong>, <strong>Sendmail</strong>,  <strong>Postfix</strong> or a custom Transport implementation of your  own, Support servers that require username &amp; password and/or  encryption, Protect from header injection attacks without stripping  request data content, Send MIME compliant HTML/multipart emails, Use  event-driven plugins to customize the library, Handle large attachments  and inline/embedded images with low memory use.</li>
<li><a href="http://phpmailer.worxware.com/" target="_blank"><strong>PHPMailer</strong></a><br />
Full featured email transfer class for PHP. PHPMailer features: Supports  emails digitally signed with S/MIME encryption, Supports emails with  multiple TOs, CCs, BCCs and REPLY-TOs, Supports Text &amp; HTML emails,  Embedded image support, Multipart/alternative emails for mail clients  that do not read HTML email, Redundant SMTP servers, SMTP  authentication, Tested on multiple <strong>SMTP</strong> servers: <strong>Sendmail</strong>,  qmail, <strong>Postfix</strong>, <strong>Gmail</strong>, Imail,  Exchange, etc.</li>
</ul>
<h3>Form</h3>
<ul>
<li><a href="http://www.phpcaptcha.org/" target="_blank"><strong>Securimage</strong></a><br />
An open-source free PHP <strong>CAPTCHA</strong> script for generating  complex images and CAPTCHA codes to protect forms from spam and abuse.  It can be easily added into existing forms on your website to provide  protection from spam bots.</li>
<li><a href="http://pof.sourceforge.net/" target="_blank"><strong>phpObjectForms</strong></a><br />
phpObjectForms is a fully object-oriented, highly customizable, easily  extendable, library for creating and processing HTML forms without  writing any HTML code. Main Features: Support for all the standard HTML  form input elements, <strong>Server-side input validation</strong> based  on regular expressions, Optional client-side JavaScript pre-validation,  Support for template-based forms. The output forms presentation is  highly tied with CSS, therefore it can be easily tuned without writing  any code but only by changing the style sheet.</li>
</ul>
<h3>HTML / CSS</h3>
<ul>
<li><a href="http://htmlpurifier.org/" target="_blank"><strong>HTML  Purifier</strong></a><br />
HTML Purifier is a standards-compliant <strong>HTML</strong> filter  library written in PHP. HTML Purifier will not only remove all malicious  code (better known as <strong>XSS</strong>) with a thoroughly audited,  secure yet permissive white list, it will also make sure your documents  are standards compliant, something only achievable with a comprehensive  knowledge of W3C’s specifications.</li>
<li><a href="http://qbnz.com/highlighter/" target="_blank"><strong>GeSHi  – Generic Syntax Highlighter</strong></a><br />
GeSHi is a <strong>syntax highlighter</strong> for HTML, written in PHP.  Basically, you input the source you want to highlight and the name of  the language you want to highlight it in, and GeSHi returns the  syntax-highlighted result. But it doesn’t stop there – GeSHi has many  powerful and unique features, including: The ability to change the  styles of any highlighted element on the fly, Use of CSS classes to  reduce the amount of output produced (GeSHi can also produce a  stylesheet to be used with a language on the fly), XHTML 1.0 Strict +  CSS2 compliance, Auto-caps/noncaps of keywords, Line numbering (both  normal and fancy forms, see the demo, and many more!</li>
</ul>
<h3>Image / Media / File</h3>
<ul>
<li><a href="http://asido.info/" target="_blank"><strong>Asido</strong></a><br />
A PHP <strong>image processing</strong> solution, with “pluggable”  drivers(adapters) for virtually any environment: GD2, Magick Wand, Image  Magick via shell, Image Magick via extension, etc. Asido offers the  following functionality: resize images, watermark images, rotate imates,  copy images, crop images, grayscale images, convert images.</li>
<li><a href="http://phpthumb.gxdlabs.com/" target="_blank"><strong>PHP  Thumb</strong></a><br />
A light-weight <strong>image manipulation</strong> library aimed at  thumbnail generation. It features the ability to resize by width,  height, and percentage, create custom crops, or square crops from the  center, and rotate the image. You can also easily add custom  functionality to the library through plugins. It also features the  ability to perform multiple manipulations per instance (also known as  chaining), without the need to save and re-initialize the class with  every manipulation.</li>
<li><a href="http://wideimage.sourceforge.net/" target="_blank"><strong>WideImage</strong></a><br />
WideImage is an object-oriented library for <strong>image manipulation</strong>.  The library focuses on often-used image operations and ease of use. It  provides a simple and unified way to loading and saving images from/to  files, strings, database and even URLs (load only, must be enabled in  PHP). Supports the most common image formats: GIF, PNG, JPEG, GD and  GD2.</li>
<li><a href="http://shiftingpixel.com/2008/03/03/smart-image-resizer/" target="_blank"><strong>Smart Image Resizer</strong></a><br />
Allows you to <strong>resize and crop</strong> any image on your website  without touching the actual image or writing any code. Simply upload  each image once at a high enough resolution and then reuse it at any  size you want, anywhere you want. Features include: Resizes JPEGs, GIFs,  and PNGs, Intelligently sharpens for crisp photos at any size, Can crop  based on width:height ratios, Can color-fill transparent GIFs and PNGs,  Built-in caching keeps image variations for optimal performance.</li>
<li><a href="http://www.verot.net/php_class_upload.htm" target="_blank"><strong>class.upload.php</strong></a><br />
This PHP script <strong>uploads files</strong> and manipulates images  very easily. The perfect script to generate thumbnails or create a photo  gallery! It can convert, resize and work on uploaded images in many  ways, add labels, watermarks and reflections and other image editing  features. You can use it for files uploaded through an HTML form, a  Flash uploader, or on local files.</li>
<li><a href="http://www.getid3.org/" target="_blank"><strong>getID3()</strong></a><br />
A PHP script that extracts useful information (such as ID3 tags,  bitrate, playtime, etc.) from MP3s &amp; other <strong>multimedia file  formats</strong> (Ogg, WMA, WMV, ASF, WAV, AVI, AAC, VQF, FLAC,  MusePack, Real, QuickTime, Monkey’s Audio, MIDI and more).</li>
<li><strong><a href="http://www.kingsquare.nl/php-psd-reader" target="_blank">PHP PSD Reader</a></strong><br />
PHP comes with built-in support to read and write images in many formats  using the GD library. However, it does not support the Photoshop image  format: PSD. This class fill partly that void by reading Photoshop PSD  image files and creating a GD image resource from the Photoshop image  bitmaps.</li>
</ul>
<h3>JavaScript / AJAX</h3>
<ul>
<li><a href="http://www.phplivex.com/" target="_blank"><strong>PHPLiveX</strong></a><br />
PHPLiveX is a lightweight PHP-JavaScript class library that helps you  integrate <strong>AJAX</strong> to your PHP applications. Without a page  is loaded again, you may call your PHP functions in the same page,  submit your form to an URL and send a request to another page with any  type of data.</li>
<li><a href="http://www.xajaxproject.org/" target="_blank"><strong>Xajax</strong></a><br />
Xajax is an open source PHP library and JavaScript engine that allows  you to easily create powerful, web-based, Ajax applications using HTML,  CSS, JavaScript, and PHP that can asynchronously call server-side PHP  functions and update content.</li>
</ul>
<h3>Microformats</h3>
<ul>
<li><a href="http://code.google.com/p/xmfp/" target="_blank"><strong>Xmf  Parser</strong></a><br />
Extensible Microformats Parser for PHP 5. Currently supported  Microformats include: <strong>xfn, rel-license, rel-tag, geo, adr,  hcard, hcalendar, hreview, hresume</strong>.</li>
<li><a href="http://www.kigkonsult.se/iCalcreator/index.php" target="_blank"><strong>iCalcreator</strong></a><br />
iCalcreator is a PHP class managing <strong>iCal</strong> formatted  files for non-calendar systems like CMS, project management systems and  other applications able to process calendar information. iCalcreator  features create, parse, edit and select calendar and calendar  components.</li>
<li><a href="http://code.google.com/p/hkit/" target="_blank"><strong>hKit</strong></a><br />
A simple PHP5 tool for extracting common <strong>microformats</strong> from a page. The page can be presented as a string or a URL, and the  result is handed back as a standard PHP array structure. hkit uses  SimpleXML for parsing, and therefore requires PHP5.</li>
<li><a href="http://code.google.com/p/transformr/" target="_blank"><strong>Transformr</strong></a><br />
A Simple set of XSLT and PHP tools for Transforming Microformats.</li>
</ul>
<h3>RSS &amp; Atom Feeds</h3>
<ul>
<li><a href="http://simplepie.org/" target="_blank"><strong>SimplePie</strong></a><br />
An open sources PHP class that provides an easy to use API for handling  all of the dirty work when it comes to fetching, caching, parsing,  normalizing data structures between <strong>RSS</strong> and <strong>Atom</strong> formats, handling character encoding translation, and sanitizing the  resulting data.</li>
</ul>
<h3>Security</h3>
<ul>
<li><a href="http://php-ids.org/" target="_blank"><strong>PHP Intrusion  Detection System (PHPIDS)</strong></a><br />
A simple to use, well structured, fast and state-of-the-art <strong>security  layer</strong> for your PHP based web application. The IDS neither  strips, sanitizes nor filters any malicious input, it simply recognizes  when an attacker tries to break your site and reacts in exactly the way  you want it to. Currently the PHPIDS detects all sorts of XSS, SQL  Injection, header injection, directory traversal, RFE/LFI, DoS and LDAP  attacks. Based on a set of approved and heavily tested filter rules any  attack is given a numerical impact rating which makes it easy to decide  what kind of action should follow the hacking attempt. This could range  from simple logging to sending out an emergency mail to the development  team, displaying a warning message for the attacker or even ending the  user’s session.</li>
</ul>
<h3>Testing &amp; Debugging</h3>
<ul>
<li><a href="http://www.phpunit.de/" target="_blank"><strong>PHPUnit</strong></a><br />
PHPUnit is a member of the  <strong>xUnit</strong> family of testing  frameworks and provides both a framework that makes the writing of tests  easy as well as the functionality to easily run the tests and analyze  their results.</li>
<li><a href="http://simpletest.sourceforge.net/" target="_blank"><strong>SimpleTest</strong></a><br />
SimpleTest is is similar to <strong>JUnit</strong>/PHPUnit. It supports  mock objects and can be used to automate the regression testing of web  applications with a scriptable HTTP Client that can parse HTML pages and  simulate things like clicking on links and submitting forms.</li>
<li><a href="http://www.php-debug.com/" target="_blank"><strong>PHP  Debug</strong></a><br />
Provides assistance in <strong>debugging</strong> PHP code, by program  trace, variables display, process time, included files, queries  executed, watch variables… This information is gathered through the  script execution and therefore are displayed at the end of the script  (in a nice floating div or a html table) so that it can be read and used  at any moment.</li>
</ul>
<h3>Web Services</h3>
<ul>
<li><a href="http://keithdevens.com/software/xmlrpc" target="_blank"><strong>XML-RPC  Library for PHP</strong></a><br />
a fully compliant XML-RPC client and server written in pure PHP. Only  requirements are PHP, and the XML parser you’re guaranteed to have if  you’re using PHP built into Apache (which most people are).</li>
<li><strong>PHP API Libraries &amp; Wrapper Classes For Popular Services</strong>
<ul>
<li><a href="http://developer.amazonwebservices.com/connect/kbcategory.jspa?categoryID=131" target="_blank"><strong>Amazon</strong> Web Services</a></li>
<li><a href="http://bingapiphp.codeplex.com/" target="_blank"><strong>Bing</strong> API PHP Library</a></li>
<li><a href="http://delicious.com/help/api" target="_blank"><strong>Delicious</strong></a> – <a href="http://www.phpdelicious.com/" target="_blank">PhpDelicious</a></li>
<li><a href="http://apidoc.digg.com/" target="_blank"><strong>Digg</strong></a> <a href="http://www.rawseo.com/news/2009/05/06/how-to-use-the-digg-api/" target="_blank">PHP API</a></li>
<li><a href="http://wiki.developers.facebook.com/index.php/PHP" target="_blank"><strong>Facebook</strong> – Official PHP Client Library</a></li>
<li><a href="http://www.phpflickr.com/" target="_blank"><strong>Flickr</strong> – phpFlickr</a></li>
<li><a href="http://www.maxmind.com/app/php" target="_blank"><strong>GeoIP</strong> PHP API</a></li>
<li><a href="http://framework.zend.com/download/webservices" target="_blank"><strong>Google</strong>’s Data APIs</a></li>
<li><a href="http://en.gravatar.com/site/implement/php" target="_blank"><strong>Gravatar</strong></a>:  <a href="http://www.talkphp.com/script-giveaway/1905-gravatar-wrapper-class.html" target="_blank">Gravatar Wrapper Class</a></li>
<li><a href="https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&amp;content_ID=developer/library_download_sdks" target="_blank"><strong>PayPal</strong> API</a></li>
<li><a href="http://recaptcha.net/plugins/php/" target="_blank"><strong>reCAPTCHA</strong> – PHP Library</a></li>
<li><a href="http://apiwiki.twitter.com/Twitter-API-Documentation" target="_blank"><strong>Twitter:</strong></a> <a href="http://emmense.com/php-twitter/" target="_blank">PHP Twitter</a>, <a href="http://simon.wippich.org/private-projects/php/twitter-class.html" target="_blank">Twitter Class</a></li>
<li><a href="http://developer.yahoo.com/php/" target="_blank"><strong>Yahoo!</strong> Web Services APIs</a></li>
</ul>
</li>
<li>Find More Web Services API at <a href="http://www.programmableweb.com/apis/directory/1?format=PHP" target="_blank">ProgrammableWeb</a></li>
</ul>
<h3>Miscellaneous</h3>
<ul>
<li><strong><a href="http://peter.upfold.org.uk/projects/wpget" target="_blank">WPGet</a></strong><br />
WPGet is a script that is designed to allow you to include a short  summary of your recent blog posts on your website. Specifically, it  works with WordPress and is great for integrating a WordPress blog into a  site that isn’t completely powered by the WP platform.</li>
</ul>
<h3>Additional Resources</h3>
<p>Here are some additional resources to help you find PHP classes,  libraries and code snippets that you may still be looking for:</p>
<ul>
<li><a href="http://www.phpclasses.org/" target="_blank">PHP Classes</a></li>
<li><a href="http://php.resourceindex.com/Functions_and_Classes/" target="_blank">The PHP Resource Index</a></li>
<li><a href="http://best-php-scripts.com/library_classes.htm" target="_blank">Best PHP Scripts</a></li>
<li><a href="http://www.codango.com/php/dir/components/" target="_blank">Codango  PHP Resource Guide</a></li>
<li><a href="http://snipt.net/public/tag/php" target="_blank">Snipt</a></li>
<li><a href="http://viralpatel.net/blogs/2009/05/15-very-useful-php-code-snippets-for-php-developers.html" target="_blank">15 very useful PHP code snippets for PHP developers</a> – ViralPatel</li>
<li><a href="http://webdeveloperplus.com/php/21-really-useful-handy-php-code-snippets/" target="_blank">21 Really Useful &amp; Handy PHP Code Snippets</a> –  Web Developer Plus</li>
<li><a href="http://www.jonasjohn.de/snippets/php/" target="_blank">Jonas  John’s PHP Snippets Collection</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://iphp.com.ua/archives/514/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Really Useful Tools For PHP Developers</title>
		<link>http://iphp.com.ua/archives/510</link>
		<comments>http://iphp.com.ua/archives/510#comments</comments>
		<pubDate>Sat, 27 Feb 2010 00:34:30 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://iphp.com.ua/archives/510</guid>
		<description><![CDATA[Whether you are a PHP novice or an experienced developer; tools that you use have direct impact on your productivity. W3Avenue has compiled a list of really useful extensions &#38; tools for PHP developers that will help you speed up development and significantly improve overall quality of your code. Accelerators eAccelerator Free open-source PHP accelerator, [...]]]></description>
			<content:encoded><![CDATA[<p>Whether you are a PHP novice or an experienced developer; tools that  you use have direct impact on your productivity. W3Avenue has compiled a  list of really useful extensions &amp; tools for PHP developers that  will help you speed up development and significantly improve overall  quality of your code.</p>
<p><span id="more-510"></span></p>
<h3>Accelerators</h3>
<ul>
<li><a href="http://eaccelerator.net/" target="_blank">eAccelerator</a><br />
Free open-source PHP accelerator, optimizer, and dynamic content cache.  It increases the performance of PHP scripts by caching them in their  compiled state, so that the overhead of compiling is almost completely  eliminated. It also optimizes scripts to speed up their execution.  eAccelerator typically reduces server load and increases the speed of  your PHP code by 1-10 time.</li>
<li><a href="http://www.php-accelerator.co.uk/" target="_blank">ionCube  PHP Accelerator</a><br />
The ionCube PHP Accelerator is an easily installed PHP Zend engine  extension that provides a PHP cache, and is capable of delivering a  substantial acceleration of PHP scripts without requiring any script  changes, loss of dynamic content, or other application compromises.</li>
</ul>
<h3>Build System</h3>
<ul>
<li><a href="http://phing.info/" target="_blank">Phing</a><br />
A project build system based on Apache Ant. You can do anything with it  that you could do with a traditional build system like GNU make, and its  use of simple XML build files and extensible PHP “task” classes make it  an easy-to-use and highly flexible build framework. Features include  running PHPUnit and SimpleTest unit tests, file transformations, file  system operations, interactive build support, SQL execution, CVS/SVN  operations, tools for creating PEAR packages, and much more.</li>
</ul>
<h3>Code</h3>
<ul>
<li><a href="http://www.beautifyphp.com/" target="_blank">BeautifyPHP</a><br />
Beautify PHP is a completely free service that allows visitors to  properly format their PHP code according to PEAR standards.</li>
<li><a href="http://pear.php.net/package/PHP_Beautifier" target="_blank">PHP  Beautifier</a><br />
This program reformat and beautify PHP 4 and PHP 5 source code files  automatically. The program is Open Source and distributed under the  terms of PHP Licence. It is written in PHP 5 and has a command line  tool.</li>
<li><a href="http://www.phpobjectgenerator.com/" target="_blank">PHP  Object Generator (POG)</a><br />
an open source PHP code generator which automatically generates clean  &amp; tested Object Oriented code for your PHP4/PHP5 application. By  generating PHP objects with integrated CRUD methods, POG gives you a  head start in any project.</li>
<li><a href="http://uml2php5.zpmag.com/en/index.php" target="_blank">UML2PHP5</a><br />
UML2PHP5 is a plugin designed to fit on the <a href="http://live.gnome.org/Dia" target="_blank">Dia diagram application</a>.  It automatically generates the PHP code structure following the  diagram’s classes.</li>
<li><a href="http://www.dpriver.com/" target="_blank">Instant SQL  Formatter</a><br />
Instant SQL Formatter is a free online SQL tidy tool. In addition to  beautifying SQL code, It can translate SQL code into C#, Java, <strong>PHP</strong>,  DELPHI and other program languages. It also allows you to find out all  database objects such as table, column, function in SQL by selecting  output format to list database object.</li>
<li><a href="http://www.phpmyedit.org/" target="_blank">phpMyEdit</a><br />
MySQL Table Editor and PHP Code Generator. Important features offered by  phpMyEdit are: table manipulation code generation; record addition,  change, view, copy and removal; table paging, sorting and filtering;  lookups into other tables (1:M bindings); permission configuration;  multiple navigation style possibilities; output design control using  CSS; logging user actions; Multilanguage support;ability to extend base  class.</li>
<li><a href="http://www.raizlabs.com/software/phpobfuscator/" target="_blank">PHP Obfuscator</a><br />
Encodes and obfuscates PHP code to make the output difficult to reverse  engineer. The application requires no pre-modifications to your code and  no additional components on your server. This product allows for  encoding of functions, variables and the removal of whitespace.</li>
<li><a href="http://www.codeeclipse.com/" target="_blank">Code Eclipse</a><br />
A PHP obfuscator that turns normal, easy to read PHP code into  gibberish; with little to no loss of speed and no loss of compatibility.</li>
</ul>
<h3>Database</h3>
<ul>
<li><a href="http://phpdataservices.codeplex.com/" target="_blank">PHP  Toolkit for ADO .NET Data Services</a><br />
Enables PHP developers to access data services created using ADO .NET  Data Services framework. The goal is to provide the similar  functionality as .NET library to access and modify the data and its  relationship using URIs which points to pieces of data integrated with  the web.</li>
<li><a href="http://propel.phpdb.org/" target="_blank">Propel</a><br />
Propel is an Object-Relational Mapping (ORM) framework for PHP5. It  allows you to access your database using a set of objects, providing a  simple API for storing and retrieving data.</li>
<li><a href="http://adodb.sourceforge.net/" target="_blank">ADOdb</a><br />
An object oriented library written in PHP that abstracts database  operations for portability. It is modeled on Microsoft’s <strong>ADO</strong>,  but has many improvements that make it unique (eg. <strong>Pivot Tables</strong>,  <strong>Active Record</strong> support, generating HTML for paging  recordsets with next and previous links, cached recordsets, HTML menu  generation, etc). Supports large number of databases including: MySQL,  PostgreSQL, Interbase, Firebird, Informix, Oracle, MS SQL, Foxpro,  Access, ADO, Sybase, FrontBase, DB2, SAP DB, SQLite, Netezza, LDAP, and  generic ODBC, ODBTP.</li>
<li><a href="http://www.doctrine-project.org/" target="_blank">Doctrine</a><br />
Doctrine is an object relational mapper (<strong>ORM</strong>) for PHP  5.2.3+ that sits on top of a powerful database abstraction layer (DBAL).  One of its key features is the option to write database queries in a  proprietary object oriented SQL dialect called Doctrine Query Language  (DQL), inspired by Hibernates HQL. This provides developers with a  powerful alternative to SQL that maintains flexibility without requiring  unnecessary code duplication.</li>
</ul>
<h3>Debugging</h3>
<ul>
<li><a href="http://www.xdebug.org/" target="_blank">Xdebug – Debugger  and Profiler Tool</a><br />
The Xdebug extension helps you debug your script by providing a lot of  valuable information. The debug information that Xdebug can provide  includes: stack traces and function traces in error messages, memory  allocation and protection for infinite recursions. Xdebug also provides:  profiling information for PHP scripts, code coverage analysis,  capabilities to debug your scripts interactively with a debug client.  You should also check: <a href="http://code.google.com/p/webgrind/" target="_blank">Webgrind</a> – Xdebug Profiling Web Frontend in PHP, <a href="http://www.bluestatic.org/software/macgdbp/" target="_blank">MacGDBp</a> – Mac OS X application that remotely debug their running PHP  applications powered by Xdebug.</li>
<li><a href="http://www.firephp.org/" target="_blank">FirePHP</a><br />
FirePHP is ideally suited for AJAX development where clean JSON and XML  responses are required. FirePHP enables you to log to your Firebug  Console using a simple PHP method call. All data is sent via response  headers and will not interfere with the content on your page.</li>
<li><a href="http://www.php-debugger.com/" target="_blank">DBG – PHP  Debugger and Profiler</a><br />
DBG is a a full-featured PHP debugger, an interactive tool that helps  you debugging php scripts. It works on a production and/or development  WEB server and allows you debug your scripts locally or remotely, from  an IDE or console.</li>
<li><a href="http://www.php-debug.com/" target="_blank">PHP Debug</a><br />
Provides assistance in debugging PHP code, by program trace, variables  display, process time, included files, queries executed, watch  variables… This information is gathered through the script execution and  therefore are displayed at the end of the script (in a nice floating  div or a html table) so that it can be read and used at any moment.</li>
<li><strong>More:</strong> <a href="http://phpdebuglib.de/" target="_blank">Debuglib</a>, <a href="http://krumo.sourceforge.net/" target="_blank">Krumo</a></li>
</ul>
<h3>Development</h3>
<ul>
<li><a href="http://matrix.squiz.net/developer/tools/php_cs" target="_blank">PHP CodeSniffer</a><br />
PHP CodeSniffer is a PHP5 script that tokenizes and “sniffs” PHP code to  detect violations of a defined set of coding standards. It is an  essential development tool that ensures that your code remains clean and  consistent. It can even help prevent some common semantic errors made  by developers.</li>
<li><a href="http://manual.phpdoc.org/" target="_blank">phpDocumentor</a><br />
Similar to Javadoc, and written in php, phpDocumentor can be used from  the command line or a web interface to create professional <strong>documentation</strong> from php source code. phpDocumentor has support for linking between  documentation, incorporating user level documents like tutorials and  creation of highlighted source code with cross referencing to PHP  general documentation.</li>
<li><a href="http://www.pdepend.org/" target="_blank">PHP Depend</a><br />
PHP Depend is software analyzer and metric tool which aims to provide  many useful information about a specified PHP project. PHP Depend can  generate a large set of software metrics from a given code base, these  values can be used to measure the quality of a software project and they  help to identify that parts of an application where a refactoring  should be applied.</li>
<li><a href="http://phplangeditor.mozdev.org/" target="_blank">phpLangEditor</a><br />
A Firefox add-on that will allow you to easily translate language files  and variables in your PHP scripts.</li>
</ul>
<h3>IDE &amp; Editors</h3>
<ul>
<li><a href="http://www.aptana.com/php" target="_blank">Aptana PHP  Development Environment</a><br />
Aptana PHP is the robust, free, open source IDE for PHP featuring  everything you need to get started fast and get even faster with  developing, testing, tuning, and deploying your PHP apps. From  pre-installed PHP servers, code assist, code templates, code generation,  debugging, refactoring, Smarty editor, database tools and more, Aptana  PHP gives you the end-to-end tools you need for PHP plus all the rest  that Aptana Studio has to offer.</li>
<li><a href="http://www.phpeclipse.com/" target="_blank">PHPEclipse</a><br />
PHPEclipse runs on all the major OS platforms and has the following  features: Syntax Coloring, Brackets Matching, Code folding, Code  Completion, PHP Manual integration, Code templates, XDebug support, DBG  Support, CVS &amp; SVN++ support.</li>
<li><a href="http://www.zend.com/products/studio/" target="_blank">Zend  Studio</a><br />
A professional-grade development environment that includes PHP code  editing, debugging, profiling, unit testing, diagnostics and more.</li>
<li><a href="http://phpanywhere.net/" target="_blank">PHPanywhere</a><br />
A web based free Integrated Development Environment for the PHP  language, in other words it is an application that gives developers all  the code editing capabilities they need to develop PHP applications  online. It includes a real-time syntax code editor with support for all  web formats and a powerful FTP editor.</li>
<li><a href="http://www.jcxsoftware.com/vs.php" target="_blank">VS.Php  For Visual Studio</a><br />
VS.Php is a PHP integrated development environment based on Visual  Studio 2008. With VS.Php you can design, develop, debug and deploy PHP  applications within the Visual Studio IDE.</li>
<li><strong>More:</strong> <a href="http://www.netbeans.org/features/php/index.html" target="_blank">NetBeans</a>,  <a href="http://www.nusphere.com/products/phped.htm" target="_blank">PhpED</a>,  <a href="http://www.phpedit.com/en" target="_blank">PHPEdit</a>, <a href="http://www.mpsoftware.dk/phpdesigner.php" target="_blank">phpDesigner</a>,  <a href="http://macromates.com/" target="_blank">TextMate</a>, <a href="http://www.activestate.com/komodo/" target="_blank">Komodo IDE</a></li>
</ul>
<h3>Security</h3>
<ul>
<li><a href="http://php-ids.org/" target="_blank">PHP Intrusion  Detection System (PHPIDS)</a><br />
A simple to use, well structured, fast and state-of-the-art security  layer for your PHP based web application. The IDS neither strips,  sanitizes nor filters any malicious input, it simply recognizes when an  attacker tries to break your site and reacts in exactly the way you want  it to. Currently the PHPIDS detects all sorts of XSS, SQL Injection,  header injection, directory traversal, RFE/LFI, DoS and LDAP attacks.  Based on a set of approved and heavily tested filter rules any attack is  given a numerical impact rating which makes it easy to decide what kind  of action should follow the hacking attempt. This could range from  simple logging to sending out an emergency mail to the development team,  displaying a warning message for the attacker or even ending the user’s  session.</li>
<li><a href="http://phpsec.org/projects/phpsecinfo/index.html" target="_blank">PhpSecInfo</a><br />
PhpSecInfo provides an equivalent to the phpinfo() function that reports  security information about the PHP environment, and offers suggestions  for improvement. It is not a replacement for secure development  techniques, and does not do any kind of code or app auditing, but can be  a useful tool in a multilayered security approach.</li>
</ul>
<h3>Setup</h3>
<ul>
<li><a href="http://www.analogx.com/contents/download/network/phpconf.htm" target="_blank">PHPConfig</a><br />
A graphical frontend to PHP’s php.ini file, where all of the  configuration of PHP takes place. The end result is that you can spend  more time on your PHP code and less on tweaking ini file. It supports  all of the standard PHP functionality, and has a special tab to handle  any 3rd party plugins.</li>
<li><a href="http://www.lighty2go.com/" target="_blank">Lighty2Go</a><br />
Lighty2Go is a, portable LightTPD, MySQL &amp; PHP (LiMP) stack on a  stick for Windows. Take it with you on your USB thumdrive and have some  fun.</li>
<li><a href="http://wiki.opensource.nokia.com/projects/PAMP" target="_blank">PAMP</a><br />
Personal AMP – Apache, MySQL and PHP – stack for the S60 mobile phone.</li>
<li><a href="http://www.wampserver.com/" target="_blank">WampServer</a><br />
Allows you to setup Apache, PHP and the MySQL database on Windows. It  also comes with PHPMyAdmin to easily manage your databases. WampServer  allows you to add as many Apache, MySQL and PHP releases as you want.</li>
<li><a href="http://www.server2go-web.de/" target="_blank">Server2Go</a><br />
A Webserver that runs out of the box without any installation and on  write protected media. This means that web applications based on  Server2Go can be used directly from CD ROM, a USB stick or from any  folder on a hard disk without the hassle of configuring Apache, PHP or  MySQL.</li>
</ul>
<h3>Testing</h3>
<ul>
<li><a href="http://www.phpunit.de/" target="_blank">PHPUnit</a><br />
PHPUnit is a member of the  xUnit family of testing frameworks and  provides both a framework that makes the writing of tests easy as well  as the functionality to easily run the tests and analyze their results.</li>
<li><a href="http://simpletest.sourceforge.net/" target="_blank">SimpleTest</a><br />
SimpleTest is is similar to JUnit/PHPUnit. It supports mock objects and  can be used to automate the regression testing of web applications with a  scriptable HTTP Client that can parse HTML pages and simulate things  like clicking on links and submitting forms.</li>
<li><a href="http://code.google.com/p/bovigo/wiki/vfsStream" target="_blank">vfsStream</a><br />
vfsStream is a stream wrapper for a virtual file system that may be  helpful in unit tests to mock the real file system. It can be used with  any unit test framework, like PHPUnit or SimpleTest.</li>
</ul>
<h3>Continuous Integration</h3>
<ul>
<li><a href="http://phpundercontrol.org/" target="_blank">phpUnderControl</a><br />
phpUnderControl is an addon application for the continuous integration  tool CruiseControl, which integrates some of the best PHP development  tools. This project aims to make your first steps with CruiseControl and  PHP as easy as possible. Therefore phpUnderControl comes with a command  line tool that performs all modifications to an existing CruiseControl  installation.</li>
</ul>
<h3>Cheet Sheets</h3>
<ul>
<li><a href="http://www.addedbytes.com/cheat-sheets/php-cheat-sheet/" target="_blank">PHP Cheat Sheet From AddedBytes</a><br />
The PHP cheat sheet is a one-page reference sheet, listing date format  arguments, regular expression syntax and common functions.</li>
<li><a href="http://www.serversidemagazine.com/cheat-sheets/PHP5/" target="_blank">PHP 5 Online Cheat Sheet</a><br />
Covering Type: Boolean, Integer, String, Array, Object/Class; String:  functions, conversion; Array: functions, conversion;  Class: definition,  member declaration, member visibility; Date/Time: functions, formats;  Predefined Variables: $_SERVER$_FILES</li>
<li><a href="http://cakephp.org/downloads/Resources" target="_blank">The  CheatSheet – CakePHP 1.2</a><br />
Includes quick reference to CakePHP Config variables, Global Functions,  Conventions, Paths and index.php file. It also provides reference for  Properties, Methods &amp; Callback functions for Models, View,  Controller and Helper classes.</li>
<li><a href="http://koivi.com/apache-iis-php-server-array.php" target="_blank">PHP $_SERVER Superglobal on Apache &amp; IIS</a><br />
A table of keys that are defined in PHP’s $_SERVER superglobal array  running on Apache and IIS servers. The purpose of this table is to allow  PHP developers an insight of what to expect if they must migrate from  one platform to another.</li>
<li><a href="http://hasin.wordpress.com/2006/06/10/smarty-cheat-sheet-version-20/" target="_blank">Smarty Cheat Sheet</a><br />
Anyone still interested in Smarty can use this cheat sheet. Contains  quick tips and reference for Smarty template designers.</li>
<li><a href="http://code.google.com/p/codeigniter-1-7-1-quick-reference-cheatsheet/" target="_blank">CodeIgniter Quick Reference Cheat Sheet</a><br />
Available in PDF &amp; PNG format; Codeigniter cheat sheet contains  library functions with parameters, helpers functions &amp; CodeIgniter  reserved names etc.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://iphp.com.ua/archives/510/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Zend Studio 7: how to automatically save before run script</title>
		<link>http://iphp.com.ua/archives/496</link>
		<comments>http://iphp.com.ua/archives/496#comments</comments>
		<pubDate>Wed, 30 Dec 2009 02:38:28 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://iphp.com.ua/?p=496</guid>
		<description><![CDATA[Everytime I run a script, the dialog box ask for saving appear. How can I configure Zend Studio(v 7.0) automatically save before running? Open Window -&#62; Preferences Open Run/Debug -&#62; Launching Find the option &#8220;Save required dirty editors before launching&#8221; (top of screen) and set it to &#8220;Always&#8221; instead of &#8220;Prompt&#8221;.]]></description>
			<content:encoded><![CDATA[<p><em>Everytime I run a script, the dialog box ask for saving appear. How can I configure Zend Studio(v 7.0) automatically save before running?</em></p>
<p>Open<strong> Window -&gt; Preferences</strong><br />
Open <strong>Run/Debug -&gt; Launching</strong><br />
Find the option &#8220;Save required dirty editors before launching&#8221; (top of screen) and set it to &#8220;Always&#8221; instead of &#8220;Prompt&#8221;.<em> </em> <em> </em></p>
]]></content:encoded>
			<wfw:commentRss>http://iphp.com.ua/archives/496/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Конвертация php-скриптов в статику</title>
		<link>http://iphp.com.ua/archives/462</link>
		<comments>http://iphp.com.ua/archives/462#comments</comments>
		<pubDate>Tue, 18 Aug 2009 14:14:30 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Soft/Tools]]></category>

		<guid isPermaLink="false">http://iphp.com.ua/?p=462</guid>
		<description><![CDATA[Предположим, у Вас есть сайт, созданный при помощи php-скриптов и базы данных MySQL. В определенное время сервер перестает нормально работать, так как перегружен посетителями &#8211; слишком много запросов. Как быть? Искусственно ограничить запросы &#8211; это значит отбросить посетителей. Наращивать мощности сервера накладно. Оптимизировать скрипты нет времени. Именно в таком случае поможет тотальная конвертация всего сайта [...]]]></description>
			<content:encoded><![CDATA[<p>Предположим, у Вас есть сайт, созданный при помощи php-скриптов и базы данных MySQL. В определенное время сервер перестает нормально работать, так как перегружен посетителями &#8211; слишком много запросов.<br />
Как быть? Искусственно ограничить запросы &#8211; это значит отбросить посетителей. Наращивать мощности сервера накладно. Оптимизировать скрипты нет времени.<br />
Именно в таком случае поможет тотальная конвертация всего сайта в статический HTML код и отдача его при помощи nginx.</p>
<p>Прежде всего необходимо определить дискретность, с которой происходит обновление информации (допустим, раз в час) и выполнять зеркалирование сайта при помощи команды wget:</p>
<p>wget -m -q -k http://мой.домен/</p>
<p>После этого полученное зеркало синхронизируем с директорией, откуда файлы обрабатывает nginx (предположим, что это /usr/local/html):</p>
<p>rsync -tgu &#8211;delete &#8211;force мой.домен /usr/local/html</p>
<p>После чего осталось синхронизировать те файлы, которые wget не отзеркалит, например, *.js &#8211; java скрипты:</p>
<p>rsync -a &#8211;include &#8216;*/&#8217; &#8211;include &#8216;*.js&#8217; &#8211;exclude &#8216;*&#8217; /путь/к/файлам/сайта/ /usr/local/html/</p>
<p>Это все. Теперь осталось запускать этот код каждый час (или реже) и всю нагрузку возьмет на себя nginx.<br />
Для того, чтобы сохранить доступ к админке CMS, необходимо повесить какой-то поддомен сайта на реальный IP и обращаться к нему. </p>
]]></content:encoded>
			<wfw:commentRss>http://iphp.com.ua/archives/462/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pinba &#8211; демон для сбора статистики о PHP-скриптах</title>
		<link>http://iphp.com.ua/archives/400</link>
		<comments>http://iphp.com.ua/archives/400#comments</comments>
		<pubDate>Wed, 06 May 2009 22:01:14 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://iphp.com.ua/?p=400</guid>
		<description><![CDATA[Документация, исходники и всё остальное доступно на pinba.org. Кратко о том, что это и для чего это: Это демон для сбора статистики о выполнении PHP-скриптов. Статистика есть двух видов &#8211; общая (скрипт, время, rusage, объем вывода и др.) и данные по таймерам. Таймеры тут один из ключевых моментов, поэтому они достойны отдельного упоминания, см. ниже. [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-family: verdana,arial,helvetica; font-size: x-small;"> Документация, исходники и всё остальное доступно на <a href="http://pinba.org/" target="_blank">pinba.org</a>.</p>
<p><strong>Кратко о том, что это и для чего это</strong>:<br />
Это демон для сбора статистики о выполнении PHP-скриптов. Статистика есть двух видов &#8211; общая (скрипт, время, rusage, объем вывода и др.) и данные по таймерам. Таймеры тут один из ключевых моментов, поэтому они достойны отдельного упоминания, см. ниже.<br />
В то же время, это не standalone-демон, данные собираются отдельным тредом в MySQL. При этом функционал MySQL используется для доступа к данным (которые видны пользователю как обычные таблицы, только read only), т.е. для выборок можно использовать обычный SQL.<br />
Статистика не хранится вечно, это просто невозможно, хранится только актуальная статистика (это понятие для всех разное и конечно это настраивается), так что возьмем для примера 1 000 000 последних запросов или 15 минут &#8211; т.е. хранятся все запросы за последние 15 минут, но не более миллиона записей. В зависимости от количества таймеров, эти данные могут занимать от 500Mb до нескольких Gb памяти. На диск, конечно, ничего не пишется.</p>
<p><strong>Подробнее о таймерах</strong>:<br />
Таймеры нужны для замеров конкретных частей кода. У таймеров есть &#8220;таги&#8221; для описания и группировки.<br />
Например, есть у вас коннект к базам &#8211; оборачиваете его в таймер с тагами &#8220;operation&#8221;=&gt;&#8221;connect&#8221;, &#8220;db&#8221;=&gt;$dbase. В результате мы получаем статистику по одному тагу &#8211; &#8220;сколько раз в секунду у нас выполняется операция connect и сколько времени она занимает&#8221; и по двум &#8211; &#8220;сколько раз в секунду у нас выполняется операция connect к конкретному серверу и сколько она занимает&#8221;.<br />
Тагов и таймеров может быть произвольное количество (но про разум не стоит забывать тоже, всё это доп. нагрузка на сервер).</p>
<p>Несколько примеров использования от Фишера: <a href="http://pinba.org/wiki/Manual:Usage_examples" target="_blank">http://pinba.org/wiki/Manual:Usage_examples</a><br />
Вся документация: <a href="http://pinba.org/wiki/Manual" target="_blank">http://pinba.org/wiki/Manual</a></p>
<p>Если вам интересно и/или есть вопросы/предложения &#8211; <a href="http://groups.google.com/group/pinba-engine/" target="_blank">welcome</a>.</span> <span class="s9" style="color: #666666;"><br />
</span></p>
]]></content:encoded>
			<wfw:commentRss>http://iphp.com.ua/archives/400/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Валидация данных в PHP при помощи filter_var</title>
		<link>http://iphp.com.ua/archives/390</link>
		<comments>http://iphp.com.ua/archives/390#comments</comments>
		<pubDate>Sun, 22 Mar 2009 06:53:43 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://iphp.com.ua/?p=390</guid>
		<description><![CDATA[Основой безопасности любого приложения является простое правило: «пришедшим от пользователя данным доверять нельзя». Для этой цели пишется довольно большое количество кода, хотя типичные задачи можно решить стандартными средствами PHP ничего не изобретая. Например, таким образом можно проверить адрес e-mail при помощи filter_var: if (filter_var($user_email, FILTER_VALIDATE_EMAIL)) { // правильный } также можно убрать лишнее, например, из [...]]]></description>
			<content:encoded><![CDATA[<p>Основой безопасности любого приложения является простое правило: «пришедшим от пользователя данным доверять нельзя». Для этой цели пишется довольно большое количество кода, хотя типичные задачи можно решить стандартными средствами PHP ничего не изобретая.</p>
<p>Например, таким образом можно проверить адрес e-mail при помощи filter_var:</p>
<pre class="brush: php;">
if (filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
// правильный
}
</pre>
<p>также можно убрать лишнее, например, из URL:</p>
<pre class="brush: php;">
$sanitized_url = filter_var($url, FILTER_SANITIZE_URL);
</pre>
<p>Хотя filter_var() есть в стандартном PHP начиная с версии 5.2.0, документация на него, <a href="http://ru.php.net/manual/ru/function.filter-var.php">особенно русская</a>, хромает.</p>
<p>Нормальная документация и примеры:<br />
— <a href="http://www.w3schools.com/php/php_ref_filter.asp">Руководство w3schools</a>.<br />
— <a href="http://mattiasgeniar.be/2009/02/07/input-validation-using-filter_var-over-regular-expressions/">Input Validation: Using filter_var() Over Regular Expressions</a>.<br />
— <a href="http://devolio.com/blog/archives/413-Data-Filtering-Using-PHPs-Filter-Functions-Part-one.html">Data Filtering Using PHP&#8217;s Filter Functions</a></p>
]]></content:encoded>
			<wfw:commentRss>http://iphp.com.ua/archives/390/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CodeIgniter vs. CakePHP</title>
		<link>http://iphp.com.ua/archives/202</link>
		<comments>http://iphp.com.ua/archives/202#comments</comments>
		<pubDate>Wed, 10 Dec 2008 23:26:16 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://iphp.com.ua/?p=202</guid>
		<description><![CDATA[Ниже находится перевод статьи Джонатана Снука (Jonathan Snook) о преимуществах и недостатках двух популярный PHP фреймворков CakePHP и CodeIgniter. Прежде чем публиковать такого рода публикации, я обычно опасаюсь за всякого рода фанатиков, которые неадекватно реагируют на подобные сравнения. Поэтому стараюсь максимально объективно подойти к повествованию. Все выводы в статье сделаны только на основании фактов. Я [...]]]></description>
			<content:encoded><![CDATA[<p><em>Ниже находится перевод <a href="http://snook.ca/archives/php/codeigniter_vs_cakephp/">статьи</a> <strong>Джонатана Снука</strong> (Jonathan Snook) о преимуществах и недостатках двух популярный PHP фреймворков <a href="http://www.cakephp.org/">CakePHP</a> и <a href="http://codeigniter.com/">CodeIgniter</a>.</em></p>
<p>Прежде чем публиковать такого рода публикации, я обычно опасаюсь за всякого рода фанатиков, которые неадекватно реагируют на подобные сравнения. Поэтому стараюсь максимально объективно подойти к повествованию. Все выводы в статье сделаны только на основании фактов.</p>
<p>Я сопоставляю две эти платформы друг против друга, но безоговорочного победителя здесь нет. Обе имеют как сильные, так и слабые стороны, а так же полные провалы в той или иной опции, которая для вас может оказаться необходимой.</p>
<h2>Зачем сравнивать?</h2>
<p>CakePHP и CodeIgniter во многом очень похожи между собой, включая то, что оба поддерживают PHP4. Говоря о преимуществах одной платформы, мы тут же можем сослаться на сильные стороны другой.</p>
<p>Они обе дают возможность работать в парадигме MVC архитектуры, что просто означает их способность разделять Модель (данные), Контроллер (который направляет данные из модели, чтобы получить представление) и Вид (то, что видит пользователь).</p>
<p>Они обе используют роутинг, который дает возможность привязывать URL к определенной функции внутри контроллера (в CakePHP это называется actions). CodeIgniter поддерживает регулярные выражения для роутинга, в то время как нужно дожидаться релиза CakePHP версии 1.2 для поддержки этой функции. <em>Поправка: CakePHP 1.1 уже поддерживает регулярные выражения для роутинга, но это не отражено в документации.</em></p>
<p>Они обе поддерживают scaffolding, который помогает автоматически сгенерировать Вид на основании Модели. В CodeIgniter scaffolding упрощен и позволяет получить доступ к подобному функционалу путем добавления ключевого слова в URL. Считаю это недостатком, т.к. часто разрабатываю персональные проекты не для публичного использования, и это ключевое слово надоедает.</p>
<p>Приступим…</p>
<p><span id="more-202"></span></p>
<h2>Подход к простоте</h2>
<p>Я убежден, что CodeIgniter притягивает благодаря своей простоте. Большая часть работы — это создать контроллер, загрузить библиотеки, получить данные из Модели и отправить результат в Вид. Все предельно понятно и вы можете наблюдать, как это работает.</p>
<p>Простота в CakePHP достигается за счет автоматизации (“automagic”). Это делает процесс кодинга быстрым, но без изучения ядра, вы просто будете сами себе задавать вопрос “что сейчас происходит?” Что касается меня, то предпочитаю понимать, как все работает. Начинающих разработчиков этот аспект просто приводит в уныние.</p>
<h2>Работа с моделями</h2>
<p>Оперирование Моделью в CodeIgniter очень наглядно и позволят применять стандартный SQL в сочетании с некоторыми командами как в этом примере:</p>
<p><code>$query = $this-&gt;db-&gt;getwhere('mytable', array(id =&gt; $id), $limit, $offset);</code></p>
<p><code>$this-&gt;db-&gt;select('title')-&gt;from('mytable')-&gt;where('id', $id)-&gt;limit(10, 20);</code><br />
<code>$query = $this-&gt;db-&gt;get();</code></p>
<p><em>Примечание: метод цепочки (chaining) применяющийся во второй части примера может работать только в PHP5.</em></p>
<p>Вы также можете создать объект модели, загрузить его и, оперируя различными методами, выполнять определенные задачи. При желании это лучше делать на уровне модели, а не контроллера, чтобы код оставался в рамках MVC.</p>
<p>У CakePHP немного другой подход, который заключается в автоматической подгрузке модели, соответствующей данному контроллеру (контроллеры и модели, имеющие одинаковые имена, связаны между собой). Вы можете отключить эту автоподгрузку и даже указать самостоятельно любые модели, которые должны быть загружены в нужный контроллер.<br />
Кроме того, CakePHP имеет в своем арсенале механизм, помогающий устанавливать связи между моделями, что помогает очень облегчить извлечение данных. Например, находясь в контроллере post_controller можно сделать следующее:</p>
<p><code>$this-&gt;Post-&gt;Comment-&gt;findAllByPostId($id)</code></p>
<p>Я выбрал этот пример, потому что он помогает продемонстрировать две разные концепции. Во-первых видно, как я получаю доступ к модели комментариев через модель поста (благодаря установленной ассоциации в модели поста). Во-вторых, благодаря методу <code>findAllByPostId</code>. CakePHP позволяет извлекать записи из базы через запросы <em>findByX</em> и <em>findAllByX</em> где <em>X</em> — это эквивалент названия поля, откуда делается выборка.<br />
Думаю, Cake неплохо демонстрирует одну из своих лучших сторон в способности автоматически подгружать ассоциированные данные. Взгляните сюда:</p>
<p><code>$this-&gt;Post-&gt;findById($id)</code></p>
<p>Этот запрос даст нам не только публикацию, но и комментарии к ней. Довольно практично.</p>
<h2>Валидация</h2>
<p>Когда работаете с моделями, вам неизбежно придется иметь дела с валидацией данных. В CodeIgniter этот функционал представлен классом validation class. С помощью него объявляется набор правил и присоединяется к объекту верификации. Объек валидации автоматически (я предполагаю) проверяет данные, поступающие от URL или формы. Разумеется, здесь вы можете сами определить, как это будет происходить. Validation class может также помочь в процессе определения сообщений об ошибках для того или иного поля.</p>
<p>В CakePHP валидация осуществляется прямо через модель двумя способами. Первый способ производит верификацию всей модели, а второй &#8211; каждого поля в отдельности и дает нам в нагрузку callback <code>beforeSave</code> для определенных полей.</p>
<p>Версия CakePHP 1.2 будет включать в себя переработанную систему валидации, для увеличения гибкости.</p>
<h2>Виды</h2>
<p>CakePHP сразу включает в себя шаблон по умолчанию и имеет две переменные: <code>title_for_layout</code> и <code>content_for_layout</code>. Любое действие автоматически привязывается к определенному виду (снова “automagic”). И до тех пор, пока вы будете называть ваши фалы особым образом, контроллеры будут автоматически связаны моделями и видами. Соответственно, обойти все это, и определить собственные шаблоны и файлы видов не представляет собой проблемы. К сожалению, нет удобного способа получить сгенерированный код вида, а отсюда и проблемы с реализацией механизма кэширования.</p>
<p>У CodeIgniter подход проще и почти сводится к обыкновенному include’ингу. Каждый файл загружается и обрабатывается. Есть и встроенный шаблонизатор (templating class), но он не проще встроенного обработчика видов (built-in view handling). Вы можете делать на манер CakePHP, постоянно включая в шаблон header и footer, но это будет только внешнее сходство. CodeIgniter позволяет заменить механизмы видов и кэширования сторонними или собственными шаблонизаторами. <em>(И всеже Smarty отлично внедряется как в CodeIgniter так и в CakePHP — прим. переводчика)</em></p>
<h2>Встроенные возможности</h2>
<p>CodeIgniter, по моему усмотрению, тут безоговорочно выигрывает благодаря таким классам как FTP, Email, File Uploading, XMLRPC, Zip encoding и многим другим.</p>
<p>CakePHP в свою очередь может похвастаться обширным репозиторием (<a href="http://bakery.cakephp.org/">the Bakery</a>). Вы можете без труда, как в CodeIgniter, подключить любые необходимые классы. Что интересно: хоть я и не пробовал этого делать, но есть возможность подключать многие классы, написанные для CI к CakePHP.</p>
<h2>Автоподгрузка</h2>
<p>CakePHP позволяет вносить в приложения обширные изменения путем модификации базового контроллера. Также вы можете создать глобальные методы, используя файл модели, что в последствии не помешает вам вносить правки уже на уровне контроллера с помощью обратных вызовов (callbacks), таких как <code>beforeFilter</code>, <code>afterFilter</code> и <code>beforeRender</code>. Похожим образом помощники (helpers) и компоненты могут быть подгружены на уровне индивидуального контроллера.</p>
<p>CodeIgniter умеет подгружать помощников, библиотеки и плагины, но делает это глобально для всего приложения. <em>(Здесь автор ошибается, т.к. в CI на уровне контроллера доступна такая конструкция: $this-&gt;load-&gt;whatever() &#8211; прим. переводчика.)</em></p>
<h2>Документация</h2>
<p>Документация — это ключ к пониманию любого фреймворка для того, чтобы разрабатывать на нем.</p>
<p>CodeIgniter имеет полный документированный список всех компонентов с каждым из их методов и параметров. У CI есть форумы и wiki с множеством фрагментов пользовательского кода.</p>
<p>CakePHP в свою очередь, не так хорошо организован. Мануал устаревший и не раскрывает того, что нам предлагает API. Кроме формата оригинальной документации можно получить оффлайн версию в CHM или PDF. Но все же у CakePHP есть Bakery, с пользовательскими статьями и компонентами. Очень помогает команд разработчиков через IRC каналы (#cakephp at irc.freenode.net). А также довольно активная <a href="http://groups.google.com/group/cake-php">Google-группа</a>.</p>
<h2>Напоследок</h2>
<p>Я довольно прагматичный человек и искренне верю, что у обоих из представленных фреймворков большое будущее. Они помогают подойти к разработке проектов более доступными средствами, чем это реализуется, например, с помощью <a href="http://www.symfony-project.com/">Symfony</a>.</p>
<p>Я лично остаюсь больше фаном CakePHP чем CodeIgniter за его “automagic”. И это достоинство более явно раскроет себя от версии к версии.</p>
<h2>Уточнение</h2>
<p>Это сравнение было основано на документации для CodeIgniter 1.5.2 и опыте использования CakePHP 1.1. Я намерено не стал касаться вопроса производительности, т.к. довольно проблематично подготовить и провести тестирование каждой опции.</p>
]]></content:encoded>
			<wfw:commentRss>http://iphp.com.ua/archives/202/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tricky Tricky Refcounts…</title>
		<link>http://iphp.com.ua/archives/49</link>
		<comments>http://iphp.com.ua/archives/49#comments</comments>
		<pubDate>Fri, 11 Jul 2008 15:46:52 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Theory]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[Occasionally a PHP engineer reports this prolem: Example Code: $my_arr = array(1,2,3); foreach ($my_arr as &#38;$val) { var_dump($val); } foreach ($my_arr as $val) { var_dump($val); } Expected Output: int(1) int(2) int(3) int(1) int(2) int(3) Actual Output: int(1) int(2) int(3) int(1) int(2) int(2) The confusion comes from the expectation that the second loop will print the [...]]]></description>
			<content:encoded><![CDATA[<p>Occasionally a PHP engineer reports this prolem:</p>
<p>Example Code:</p>
<pre class="brush: php;">
$my_arr = array(1,2,3);
foreach ($my_arr as &amp;$val) {
    var_dump($val);
}
foreach ($my_arr as $val) {
    var_dump($val);
}
</pre>
<p>Expected Output:</p>
<pre class="brush: php;">
int(1)
int(2)
int(3)
int(1)
int(2)
int(3)
</pre>
<p>Actual Output:</p>
<pre class="brush: php;">
int(1)
int(2)
int(3)
int(1)
int(2)
int(2)
</pre>
<p>The confusion comes from the expectation that the second loop will print the last element of the array as int(3) rather than int(2).  The initial reaction is usally “this is a PHP bug”, but it really isn’t.  There are two key aspects to this code to watch out for; 1) The scope of foreach variables is not limited to the foreach block. 2) Foreach loops do not unset foreach variables at the start of the block.</p>
<p>With this in mind we can see that at the end of the first loop, $val is a reference to the last element of $my_arr.  Each iteration over the foreach loop can be thought of as an assignment operation, in this case by reference:</p>
<pre class="brush: php;">
$val = &amp;$my_arr[0]
$val = &amp;$my_arr[1]
$val = &amp;$my_arr[2]
// last iteration $val is a reference to $my_arr[2]
</pre>
<p>As we step through each iteration of the second foreach loop we see the assignments of $val to each element of the $my_arr (assigned by value this time).</p>
<pre class="brush: php;">
$val = $my_arr[0]
$val = $my_arr[1]
$val = $my_arr[2]
</pre>
<p>But if we you recall $val is really a reference to the last element of $my_arr because it carries over from the first foreach loop, so the actual assignment looks more like:</p>
<pre class="brush: php;">
$my_arr[2] = $my_arr[0]
$my_arr[2] = $my_arr[1]
$my_arr[2] = $my_arr[2]
</pre>
<p>Thus we end up with $my_array being set as such on each iteration:</p>
<pre class="brush: php;">
// (array(1,2,1))  first element is set to value of last
$my_arr[2] = $my_arr[0]

// (array(1,2,2))  second element is set to value of last
$my_arr[2] = $my_arr[1]

// (array(1,2,2))  last element is set to value of itself
$my_arr[2] = $my_arr[2]
</pre>
<p>Note that the last assignment is really assigning the last element to itself!</p>
<p>Because PHP5 handles variables with a copy on write algorithm, it’s typically not necessary to do any assignmnents by reference with performance gains in mind (as was the case with a lot of PHP4 code).  The above code can be made to function as the expected case by placing an unset($var) between the foreach loops, or not iterating over references and instead assigning the values of $my_arr explicitly by index or key values.  References should be used by care  and only when necessary.  When code like this is present in global scope or large functions it may affect future code in seemingly unpredictable ways.</p>
]]></content:encoded>
			<wfw:commentRss>http://iphp.com.ua/archives/49/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>О вечном: деревья&#8230; (db_tree)</title>
		<link>http://iphp.com.ua/archives/27</link>
		<comments>http://iphp.com.ua/archives/27#comments</comments>
		<pubDate>Tue, 13 Nov 2007 19:41:45 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[tree]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[Ссылки: http://forum.dklab.ru/sql/php/IerarhicheskieStrukturiVBd.html http://www.livejournal.com/users/demiurg/53125.html http://e-taller.net/dev/dbtree/ http://sdm.viptop.ru/articles/sqltrees.html http://www.webscript.ru/stories/04/09/01/8197045 http://www.webscript.ru/stories/05/01/24/6319028 http://phpclub.ru/talk/showthread.php?threadid=70821 http://phpclub.ru/faq/wakka.php?wakka=chpu&#38;v=gls http://phpclub.ru/faq/wakka.php?wakka=Tree&#38;v=uof http://dev.mysql.com/tech-resources/articles/hierarchical-data.html]]></description>
			<content:encoded><![CDATA[<p>Ссылки:</p>
<p><a target="_blank" href="http://forum.dklab.ru/sql/php/IerarhicheskieStrukturiVBd.html">http://forum.dklab.ru/sql/php/IerarhicheskieStrukturiVBd.html</a><br />
<a target="_blank" href="http://www.livejournal.com/users/demiurg/53125.html">http://www.livejournal.com/users/demiurg/53125.html</a><br />
<a target="_blank" href="http://e-taller.net/dev/dbtree/">http://e-taller.net/dev/dbtree/</a><br />
<a target="_blank" href="http://sdm.viptop.ru/articles/sqltrees.html">http://sdm.viptop.ru/articles/sqltrees.html</a><br />
<a target="_blank" href="http://www.webscript.ru/stories/04/09/01/8197045">http://www.webscript.ru/stories/04/09/01/8197045</a><br />
<a target="_blank" href="http://www.webscript.ru/stories/05/01/24/6319028">http://www.webscript.ru/stories/05/01/24/6319028</a><br />
<a target="_blank" href="http://phpclub.ru/talk/showthread.php?threadid=70821">http://phpclub.ru/talk/showthread.php?threadid=70821</a><br />
<a target="_blank" href="http://phpclub.ru/faq/wakka.php?wakka=chpu&amp;v=gls">http://phpclub.ru/faq/wakka.php?wakka=chpu&amp;v=gls</a><br />
<a target="_blank" href="http://phpclub.ru/faq/wakka.php?wakka=Tree&amp;v=uof">http://phpclub.ru/faq/wakka.php?wakka=Tree&amp;v=uof</a><br />
<a target="_blank" href="http://dev.mysql.com/tech-resources/articles/hierarchical-data.html">http://dev.mysql.com/tech-resources/articles/hierarchical-data.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://iphp.com.ua/archives/27/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Кропотливая оптимизация PHP-приложений (рассматриваю PHP5, но большинство справедливо и для 4-й ветки)</title>
		<link>http://iphp.com.ua/archives/20</link>
		<comments>http://iphp.com.ua/archives/20#comments</comments>
		<pubDate>Mon, 05 Nov 2007 16:49:19 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[optimization]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[Не то чтобы &#8220;очень классная статья&#8221;, но начинающим будет полезна (взято здесь http://www.habrahabr.ru/blog/webdev/19129.html) Когда во сне снится &#8220;ой а если сервера не хватит&#8230;&#8221; Для начала, Доброй Ночи. Пишу что-то полезное вроде впервые (если не считать разного рода полу-тестов в моём блоге). Человек я допытливый до жути, неожиданно в голову пришло, что могу помочь сэкономить кому-то [...]]]></description>
			<content:encoded><![CDATA[<p>Не то чтобы &#8220;очень классная статья&#8221;, но начинающим будет полезна (взято здесь <a href="http://www.habrahabr.ru/blog/webdev/19129.html">http://www.habrahabr.ru/blog/webdev/19129.html</a>)</p>
<h1>Когда во сне снится &#8220;ой а если сервера не хватит&#8230;&#8221;</h1>
<p>Для начала, Доброй Ночи. Пишу что-то полезное вроде впервые (если не считать разного рода полу-тестов в моём блоге). Человек я допытливый до жути, неожиданно в голову пришло, что могу помочь сэкономить кому-то много времени <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .</p>
<p>В общем когда на PHP создаются достаточно большие проекты (&gt;100000 строк кода) желание сделать &#8220;правильно&#8221; то, что было сделано давно грозит повергнуть всё в хаос. По крайней мере для новых программистов, которые могут прийти в компанию через неделю, месяц, год&#8230; Решение &#8211; четкая систематизация с самого начала и установление жестких архитектурных правил. Для себя я решил &#8211; не используя фреймворки писать буду только &#8220;Hello World&#8221;-сайты. Не мудрствуя лукаво когда подумал о фреймворках полистал, почитал, но решил отдаться-таки зенду с его <a href="http://framework.zend.com/">ZendFramework</a>. Добротный он, хотя и изменений я в нём для себя сделал огромное количество.</p>
<p>В таком решении на ряду со всеми возможными плюсами и удобством неожиданно встаёт вопрос-стена: теперь у меня бизнес логика занимает, наверное, где-то вовсе 1-2% от времени исполнения всей программы. Плата за удобство и ООП (или &#8220;удобство ООП&#8221;? Наверное даже просто &#8220;удобство&#8221; или просто &#8220;ООП&#8221; &#8211; это почти одно и то же <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ) &#8211; огромное количество сопутствующего и управляющего кода.<br />
<span id="more-20"></span></p>
<p>В общем когда я делал новый проект &#8211; была цель &#8211; не менее 50 запросов в секунду на захудалом Celeron 2.6GHz. Т.е. около 0.02сек на запрос, включая mysql и так далее тому подобное. За время создания проекта я его умудрялся разгонять в несколько раз какими-то улучшениями. Какими? Налейте чашечку кофе &#8211; и добро пожаловать в мир мудрого девелопинга <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Сразу скажу &#8211; получилось.</p>
<h1>Оптимизация от А до Я. Рецепт супчика от MockSoul <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </h1>
<h2>Этап 0. Готовимся</h2>
<p>Окружение? Моя наилюбимейшая схема:</p>
<ol>
<li>LigHTTPd. Под линуксом. Со включенным sys-epoll;</li>
<li>PHP5. Через FastCGI. PHP должен быть собран с поддержкой CGI, sharedmem (или threads, лучше sharedmem &#8211; а и то и другое сразу не скомпилится <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ). Дикий пример с чем я собираю пхп:
<p>./configure&#8217; &#8216;&#8211;prefix=/usr/lib/php5&#8242; &#8216;&#8211;host=i686-pc-linux-gnu&#8217; &#8216;&#8211;mandir=/usr/lib/php5/man&#8217; &#8216;&#8211;infodir=/usr/lib/php5/info&#8217; &#8216;&#8211;sysconfdir=/etc&#8217; &#8216;&#8211;cache-file=./config.cache&#8217; &#8216;&#8211;disable-cli&#8217; &#8216;&#8211;enable-cgi&#8217; &#8216;&#8211;enable-fastcgi&#8217; &#8216;&#8211;disable-discard-path&#8217; &#8216;&#8211;disable-force-cgi-redirect&#8217; &#8216;&#8211;with-config-file-path=/etc/php/cgi-php5&#8242; &#8216;&#8211;with-config-file-scan-dir=/etc/php/cgi-php5/ext-active&#8217; &#8216;&#8211;without-pear&#8217; &#8216;&#8211;disable-bcmath&#8217; &#8216;&#8211;with-bz2&#8242; &#8216;&#8211;disable-calendar&#8217; &#8216;&#8211;disable-ctype&#8217; &#8216;&#8211;without-curl&#8217; &#8216;&#8211;without-curlwrappers&#8217; &#8216;&#8211;disable-dbase&#8217; &#8216;&#8211;disable-exif&#8217; &#8216;&#8211;without-fbsql&#8217; &#8216;&#8211;without-fdftk&#8217; &#8216;&#8211;disable-filter&#8217; &#8216;&#8211;disable-ftp&#8217; &#8216;&#8211;with-gettext&#8217; &#8216;&#8211;without-gmp&#8217; &#8216;&#8211;disable-hash&#8217; &#8216;&#8211;disable-ipv6&#8242; &#8216;&#8211;disable-json&#8217; &#8216;&#8211;without-kerberos&#8217; &#8216;&#8211;enable-mbstring&#8217; &#8216;&#8211;with-mcrypt&#8217; &#8216;&#8211;without-mhash&#8217; &#8216;&#8211;without-msql&#8217; &#8216;&#8211;without-mssql&#8217; &#8216;&#8211;with-ncurses&#8217; &#8216;&#8211;with-openssl&#8217; &#8216;&#8211;with-openssl-dir=/usr&#8217; &#8216;&#8211;disable-pcntl&#8217; &#8216;&#8211;without-pgsql&#8217; &#8216;&#8211;without-pspell&#8217; &#8216;&#8211;without-recode&#8217; &#8216;&#8211;disable-simplexml&#8217; &#8216;&#8211;enable-shmop&#8217; &#8216;&#8211;with-snmp&#8217; &#8216;&#8211;disable-soap&#8217; &#8216;&#8211;enable-sockets&#8217; &#8216;&#8211;without-sybase&#8217; &#8216;&#8211;without-sybase-ct&#8217; &#8216;&#8211;disable-sysvmsg&#8217; &#8216;&#8211;disable-sysvsem&#8217; &#8216;&#8211;disable-sysvshm&#8217; &#8216;&#8211;with-tidy&#8217; &#8216;&#8211;disable-tokenizer&#8217; &#8216;&#8211;disable-wddx&#8217; &#8216;&#8211;disable-xmlreader&#8217; &#8216;&#8211;disable-xmlwriter&#8217; &#8216;&#8211;without-xmlrpc&#8217; &#8216;&#8211;without-xsl&#8217; &#8216;&#8211;disable-zip&#8217; &#8216;&#8211;with-zlib&#8217; &#8216;&#8211;disable-debug&#8217; &#8216;&#8211;enable-dba&#8217; &#8216;&#8211;without-cdb&#8217; &#8216;&#8211;without-db4&#8242; &#8216;&#8211;without-flatfile&#8217; &#8216;&#8211;with-gdbm&#8217; &#8216;&#8211;without-inifile&#8217; &#8216;&#8211;without-qdbm&#8217; &#8216;&#8211;with-freetype-dir=/usr&#8217; &#8216;&#8211;with-t1lib=/usr&#8217; &#8216;&#8211;disable-gd-jis-conv&#8217; &#8216;&#8211;with-jpeg-dir=/usr&#8217; &#8216;&#8211;with-png-dir=/usr&#8217; &#8216;&#8211;without-xpm-dir&#8217; &#8216;&#8211;with-gd&#8217; &#8216;&#8211;with-ldap&#8217; &#8216;&#8211;without-ldap-sasl&#8217; &#8216;&#8211;with-mysql=/usr&#8217; &#8216;&#8211;with-mysql-sock=/var/run/mysqld/mysqld.sock&#8217; &#8216;&#8211;without-mysqli&#8217; &#8216;&#8211;without-pdo-dblib&#8217; &#8216;&#8211;with-pdo-mysql=/usr&#8217; &#8216;&#8211;without-pdo-odbc&#8217; &#8216;&#8211;without-pdo-pgsql&#8217; &#8216;&#8211;without-pdo-sqlite&#8217; &#8216;&#8211;with-readline&#8217; &#8216;&#8211;without-libedit&#8217; &#8216;&#8211;with-mm&#8217; &#8216;&#8211;without-sqlite&#8217;</p>
<p>Грамотно прикручиваем к lighttpd, а не абы как:</p>
<pre>fastcgi.server = (     ".php" =&gt; (         "localhost" =&gt; (             "socket"          =&gt; "/tmp/php5-gmru-sandbox-mocksoul-lighttpd.sock" [#1],             "bin-path"        =&gt; "/usr/lib/php5/bin/php-cgi -c " + "/path/to/application/config/php_config_dir" [#2],             "min-procs"       =&gt; 1 [#3],             "max-procs"       =&gt; 1 [#3],             "bin-environment" =&gt; (                 "PHP_FCGI_CHILDREN" =&gt; "32" [#4],                 "PHP_FCGI_MAX_REQUESTS" =&gt; "3200" [#5]             )         )     ) )</pre>
<p>([#1], [#2], &#8230; &#8211; так буду ссылаться на комментарии к коду. Если хотите взять код &#8211; такие пометки надо будет стереть. Ниже в коде буду придерживаться такой же схемы)</p>
<ul>
<li>[#1] &#8211; unix-сокеты много шустрее чем tcp-сокеты. Так что используйте их только если в TCP нет серьёзной необходимости (или, хаха, под Windows <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> )</li>
<li>[#2] &#8211; тут я просто показал пример как можно конфиг пхп прикручивать к разному хосту (через -c указываем на папку с php.ini)</li>
<li>[#3] &#8211; min-procs и max-procs ДОЛЖНЫ БЫТЬ = 1!! Почему? Потому что далее я скажу про кеширование байткода. Кеш будет нелогичен при кол-ве процессов пхп более 1</li>
<li>[#4] &#8211; магический танец. Просим php запустить 32 потока в одном процессе для обработки запросов от lighttpd. Важно: если поставить, например, 10 и все 10 будут заняты каким-то диким 10-секундно-выполняющимся-скриптом &#8211; lighttpd будет отдавать 500 ошибку! Т.е. количество потоков не увеличивается в реалтайме &#8211; ставьте 32, 64 или, даже, 128 (работает это как threadpool)</li>
<li>[#5] &#8211; просим убить поток и создать новый через энное количество запросов. На всякий случай, ведь php не идеален <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</li>
</ul>
</li>
<li>Opcode Cacher. Или кешер байткода. Или &#8220;что за дибилизм &#8211; парсить одни и те же файлы при каждом запросе?!&#8221;. Очень (ОЧЕНЬ!) рекомендую APC (Alternative PHP Cache) который лежит в <a href="http://pecl.php.net/APC">PECL</a>. Можно так же eAccelerator или даже ZendOptimizer. Вкусы разные бывают.. Но при выборе между eAccelerator и APC &#8211; я рекомендую APC. Почему? Да хотя бы за возможность положить что угодно в shmem сегмент <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . Ниже расскажу.</li>
</ol>
<h2>Этап 1. Пишем</h2>
<p>Сначала пишем. Пишем и крутим в голове мысли о том как что-то сделать более разумным и быстрым сразу. Чтобы потом не отвлекаться (вообще это наверное совершенно естественное желание любого уважающего себя программиста %))</p>
<p>Моменты на которые сразу нужно обращать внимание:</p>
<ol>
<li>Вам, наверное, почти не нужно будет использовать require и include. В основном &#8211; require_once и include_once.</li>
<li>Для итерации по массивам, их изменению и фильтрации &#8211; учимся использовать array_* функции в пхп. Особенно лямбда-функции:
<pre>&lt;?php          $arr = array('that', 'is', 'this'); array_walk($arr, create_function('&amp;$v,$k', '$v = $v . " yeah";'); print_r($arr);  // outputs: // Array // ( //   [0] =&gt; that yeah //   [1] =&gt; is yeah //   [2] =&gt; this yeah // )  // А вы бы сделали это циклом? Ай-ай-ай...  ?&gt;</pre>
</li>
<li>Передача переменной по ссылке (например $a=1; call_func(&amp;$a)) &#8211; не влияет на быстродействие. Передача массивов по ссылке &#8211; влияет чуть-чуть. Передача классов &#8211; влияет очень. Я это к тому &#8211; что не передавайте ничего по ссылке надеясь ускорить программу. Передавайте по ссылкам только когда вам это _действительно_ нужно</li>
<li>Делайте классы статическими если можно. Т.е. если для работы класса закрытая инстанция в общем-то и не нужна.</li>
<li>Комментировать можно сколько хочется &#8211; кешер байткода все равно комментарии игнорирует. На быстродействие это влияет.. хм.. на 0.000001% <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
<li>Избегайте глубоких рекурсий. Стандартную задачу &#8211; взять список файлов включая поддирректории можно сделать и без рекурсии вовсе =)</li>
<li>Прочитайте грамотные доки. Документацию того же ZendFramework &#8211; там много чего полезного даже тем кто фреймворк не использует и использовать не собирается</li>
<li>Старайтесь делить код на логические блоки. Так, чтобы можно было взять 10-20 строчек подряд и сказать &#8211; вот тут я делаю ТОЛЬКО ЭТО. Взять другие 10-20 &#8211; и сказать а тут я делаю ТОЛЬКО ДРУГОЕ. Кол-во строчек которые надо брать, конечно, зависит от вас. Но лучше чтобы блоки были не более чем по 30-40 строк. Разбивайте программу и любой блог на инициализацию, настройку, работу, сохранение результата (в переменную скажем). При чём тут скорость? Через полгода поймёте <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .</li>
<li>О том &#8220;Может сделать мне $a = &#8220;some $v inline&#8221; или $a = &#8220;some&#8221; . $v . &#8220;var&#8221; даже думать не стоит. Лично я (имхо) нахожу абсолютно дибильным вставку переменных прямо в строки. Лучшая читаемость:
<ul>
<li>$var = &#8216;some&#8217; . $in . &#8216;li&#8217; . $ne . &#8216; variable&#8217;;</li>
<li>$var = sprintf(&#8216;some %sli%s variable&#8217;, $in, $li);</li>
</ul>
</li>
<li>Используйте константы для того что никогда не меняется. Они парсятся в самом начале и лежат вообще в другом куске памяти чем обычные переменные. Конструкции вида $str = &#8216;some&#8217; . STR_CONSTANT и выглядят к тому же лучше. Особо грамотно &#8211; перенос строки. Обзывают его по-разному, я же люблю NL (NewLine) или CRLF(CarretReturnLineFeed)</li>
<li>Не забывайте что foreach может и не делать копию массива <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />
<pre>foreach ($arr as $key =&gt; &amp;$val) { ... }</pre>
</li>
<li>Как это ни парадоксально но вот такой момент меня в пхп совсем убивает: is_null() &#8211; придумана идиотом. if (null === $var) или if ($var === null) быстрее чем if (is_null($var))&#8230; дибилизм. Не используйте is_null() <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
<li>Регулярные выражения, работу со строками с помощью str_* функций и прочее оставляю на вашей совести как выходящее за рамки этой и без того раздутой статьи <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
</ol>
<h2>Этап 2. Размышляем о возможных тратах времени</h2>
<p>Так.. вот написали вы чего-нибудь. А теперь давайте посмотрим что обычно отнимает достаточно дофига времени без вашей бизнес-логики:</p>
<ol>
<li>Коннект к БД</li>
<li>Обработка тонны require_once и include_once</li>
<li>Сами запросы к БД</li>
<li>Где-то храним конфиг и парсим его каждый раз? Используем модели БД и инициализируем их каждый раз? Вообще посмотрите как много одинакового мы делаем каждый запрос!!</li>
<li>Что-то делаем с файловой системой? А зачем? Лично я думаю что можно чуть ли не любой проект написать с вообще отсутствующим IO (конечно, кроме того что будет использовать БД и тп). Не нужно ничего хранить в файловой системе. Мелкое. Большое (какой-нибудь гиговый проиндексированный файл) &#8211; нужно</li>
</ol>
<p>Это я все отсортировал по важности. А теперь по порядку по каждому ненасытному моменту:</p>
<h3>Коннект к БД</h3>
<p>Всё просто &#8211; если владеете сервером &#8211; используйте постоянные подключения! PDO_MYSQL, MYSQL &#8211; все это умеют )</p>
<h3>Обработка тонны require_once и include_once</h3>
<p>Вот тут начинается веселье =). Для начала я взял посмотрел сколько файлов у меня включаются при ЛЮБОМ запросе в ZendFramework. Оказалось &#8211; чуть менее 300 (!!!!). Если не использовать байткод кешер &#8211; это будет вообще ненормально долгая процедура.</p>
<p>Решение &#8220;влоб&#8221; нашлось само собой &#8211; запихать всё это в один файл. Встал вопрос &#8211; а как узнать что у нас всегда инклудится &#8211; а что иногда? Вообще размышлять в тот момент особо времени не было поэтому и этот аспект я решил &#8220;влоб&#8221; )</p>
<p>Дикий результат &#8211; <a href="http://www.mocksoul.ru/pub/dev/mkzend.phps">http://www.mocksoul.ru/pub/dev/mkzend.phps</a></p>
<p>Там:</p>
<ul>
<li>Насколько часто обращение к файлу &#8211; смотрим через APC кеш по статистике</li>
<li>Рисуем табличку</li>
<li>Изменяем зенд автоматом <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . Типа вырезаем все require_once, комментарии, открывающие и закрывающие пхп теги, лишние пробелы&#8230; издеваемся короче <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Смотрите исходник</li>
<li>Сохраняем получившеся гигантский скрипт в файлик&#8230; )</li>
</ul>
<p>Скрипт абсолютно нестабилен и заточен под один проект. Запускать надо через браузер, чтобы APC отработал. Просто как пример. У вас работать не будет со 100% вероятностью =).</p>
<p>Как оказалось &#8211; 300 файлов парсились 2 сек, из байткешера вытаскивались за 0.3 сек, а сгенерированый суперфайл большой парсится 0.7сек а из кеша вытягивается за 0.003сек. Проект сразу разогнался почти в 3 раза <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . Маньячная оптимизация, однако. Метод подходит для production-сервера, т.к. девелопить библиотеки которые из другого файла грузятся &#8211; невозможно.</p>
<h3>Запросы к БД</h3>
<p>Пройдите экскурс в ДБА и начните, наконец, использовать MYSQL_QUERY_CACHE. В my.cnf пишем query_cache_size = 100M. За кешем следим путём show status like &#8216;qcache%&#8217;. Ещё очень плотно читаем доки MySQL относительно Query Cache</p>
<h3>Хватит делать одно и тоже &#8211; кешируйте!</h3>
<p>Прочитали конфиг? Распарсили? Получили готовенький массив? Ну и зачем парсить его снова? ) У вас же есть &#8211; shared memory под рукой в виде APC! <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Невероятно быстрая скорость работы.. Храните в нём все что только можно &#8211; конфигурацию, собранные объекты, результаты запросов а-ля &#8220;describe table&#8221; (это прерогатива Zend_Db_Table_*). Из кеша данные берутся с невообразимой скоростью &#8211; 0.000001с где-то. В памяти, если не дублировать ничего, можно сохранить просто дофига данных. Помните, что 1 гиг &#8211; это огромная куча возможной информации. Не используйте IO в файловую систему для этого &#8211; лучше память. В зависимости от вашей квалификации &#8211; от 10 до 100% прироста скорости. Смотрите ниже про APD <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<h3>Зачем вам ФС?</h3>
<p>Используйте ФС как хранитель чего угодно, только если это не влазит в память. Даже если пишите лог или статистику запросов &#8211; ложите в APC! И сохраняйте, скажем, каждые 5 минут на винт.</p>
<h2>Этап 3. Устали размышлять о тратах времени. Хотим график перед глазами!</h2>
<p>Это для меня оказалось весьма ценным открытием. В общем пошаговый гид:</p>
<ol>
<li>Нам нужен <a href="http://pecl.php.net/apd">PECL APD</a> (Advanced PHP Debugger)</li>
<li>Конфигурим dumpdir для apd в конфиге. Что-то вроде:
<pre>zend_extension=/usr/lib/php5/lib/php/extensions/no-debug-non-zts-20060613/apd.so apd.dumpdir="/tmp/php-apd-dump"</pre>
</li>
<li>В самом главном файлике пишем в сааамом верху apd_set_pprof_trace();, тем самым включая дамп профилера</li>
<li>Делаем 1-100 запросов на сервер. Каждый раз будет сохранятся новый файлик в нашей /tmp/php-apd-dump</li>
<li>Теперь мы можем смотреть результаты профилера либо прямо в консоли &#8211; вместе с apd идёт скриптик pprofp</li>
<li>А ещё можем сделать супервещь &#8211; преобразовать в более унифицированный формат <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . С APD кроме pprofp есть ещё pprof2calltree. Она преобразует дампы профилера в формат, понимаемый cachegrind и KCacheGrind в частности. Полученный файлик открываем в kcachegrind &#8211; и рукоплещем от удовольствия.</li>
</ol>
<p>В целом &#8211; обычный такой профилер получается. Вот только для PHP я раньше такого не делал <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<h2>Этап 4. Проверяем</h2>
<p>Проверять скорость простыми запросами на 1 урл при помощи ab или ab2 &#8211; глупо.</p>
<p>Более логичный вариант &#8211; сделать список всех (или не всех <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ) урлов, положить в текстовый файлик, взять <a href="http://www.joedog.org/JoeDog/Siege">Siege</a> и тестить. Во время теста следить за TPS (TransactionsPerSecond) на винты (например при помощи iostat из пакета sysstat), следить за загрузкой процессоров, смотреть чтобы в конце не было ответов сервера отличных от 2хх.</p>
<h1>Зачем это всё</h1>
<p>Так сильно пытаться все ускорить нужно когда проект разрастается. Увеличение быстродействия на 10% на 1 сервере даёт прирост в скорости равный 10%. А если у вас уже 10 серверов &#8211; то 10%-ое увеличение быстродействие будет равно добавлению ещё одного 11-го сервера. Т.е. +100% в пересчете на 1 сервер. Это много. Это деньги. И это более высокий порог входа для конкурентов <img src='http://iphp.com.ua/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .</p>
]]></content:encoded>
			<wfw:commentRss>http://iphp.com.ua/archives/20/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
