Apache
RSSPosts: 2
Local Windows XP, XAMPP Apache server, NuSphere PhpED debugger, Zend Framework mod_rewrite PHP Code Setup
INTRODUCTION
How to setup a Zend Framework PHP web site on a local machine Windows XP machine using XAMPP and PhPED Debugger
GOALS
- Run the site from http://localhost or some equivalent on the local machine
- Run the site in PhpED debugger
WHY THIS ISN’T LIKE A NORMAL PHP WEB SITE
- the Zend Framework URL rewrites setup will KILL you on a local machine. As in, you will either want to commit suicide or homicide trying to set this up.
- If this example uses a slash at the end of a directory path or URI, USE THE SLASH.
- Every period, comma and slash is important!
- You might be able to make this work without the punctuation, but if your setup is broken, check the punctuation!
OPERATING SYSTEM
WINDOWS XP and appropriate 150 or so Microsoft updates.
APACHE SERVER, MYSQL DATABASE
XAMPP Package xampp-win32-1.7.1.exe
It’s not the most recent but I know it works with Joomla and it works for this project as well.
Extract to c:\ which creates c:\xampp
Using the XAMPP control panel, install MySql and Apache as Windows services.
WHENEVER YOU MAKE CHANGES TO
C:/xampp/apache files,
RESTART Apache
using Windows Services
or at CMD “c:\xampp\apache\bin\httpd.exe” -k restart
DEBUGGER IDE
NuSphere PhpED Professional 5.95 build 5970
Install using all defaults to c:\program files\nusphere
WEB SITE ZEND FRAMEWORK SETUP
Extract root of web site to c:\xampp\htdocs\myapp, where myapp is the placeholder for your web site’s root directory. A correctly architected Zend project will not require an index.php in the root directory. index.php is forwarded to public\index.php. This project (that we’re calling myapp, and that I inherited), does not use public for index.php. index.php is in the root directory. It does use .htaccess on a shared server BUT DOES NOT use .htaccess here.
ARCHITECTURE
I AM NOT RECOMMENDING THIS ARCHITECTURE. I am only documenting how to debug it.
c:/xampp/htdocs/myapp/application
configs, models, views, Bootstrap.php
c:/xampp/htdocs/myapp/public
resources such as images and videos
c:/xampp/htdocs/myapp/public/index.php
The index.php that invokes the Bootstrap
myapp/.htaccess or myapp/public/.htaccess
THERE ARE NONE. Virtual Hosts overrides .htaccess.
c:/xampp/htdocs/myapp/php.ini:
php_flag magic_quotes_gpc off php_flag register_globals off php_value include_path .;c:/xampp\htdocs\myapp\application;
c:/xampp/htdocs/myapp/application/configs/application.ini*
* USE FULL PATHS rather than hybrid concatenations off APPLICATION_PATH
[production] phpSettings.display_startup_errors = 0 phpSettings.display_errors = 0 phpSettings.date.timezone = "UTC" includePaths.library = c:\xampp\htdocs\myapp\application\library bootstrap.path = c:\xampp\htdocs\myapp\application\Bootstrap.php bootstrap.class = "Bootstrap" resources.frontController.controllerDirectory = c:\xampp\htdocs\myapp\application\controllers resources.db.adapter = PDO_MYSQL resources.db.params.host = localhost resources.db.params.username = root resources.db.params.password = resources.db.params.dbname = myapp staging : production] [testing : production] phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1 [development : production] phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1
WINDOWS ENVIRONMENT PATH
Has NuSphere items from installation but NO extra definitions.
Paths are defined in php.ini, application.ini, hosts and httpd.conf files.
APACHE CONFIGURATION
c:/xampp/apache/conf/httpd.conf
Many of these are defaulted to these values. Some are not.
Enable mod_rewrite
LoadModule rewrite_module modules/mod_rewrite.so
Include vhosts conf:
Include conf/extra/httpd-vhosts.conf
Set AllowOverride to All — this directive affects whether Apache will read .htaccess.
It is actually only necessary in vhosts (instructions below). However this setup is SO touchy that
I would go ahead and set every AllowOverride to All regardless of which element it’s in.
Entire c:/xampp/apache/conf/httpd.conf:
ThreadsPerChild 250
MaxRequestsPerChild 0
ServerRoot "C:/xampp/apache"
Listen 80
LoadModule actions_module modules/mod_actions.so
LoadModule alias_module modules/mod_alias.so
LoadModule asis_module modules/mod_asis.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule authn_alias_module modules/mod_authn_alias.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_dbd_module modules/mod_authn_dbd.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule cache_module modules/mod_cache.so
LoadModule mem_cache_module modules/mod_mem_cache.so
LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule charset_lite_module modules/mod_charset_lite.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule dav_module modules/mod_dav.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule dir_module modules/mod_dir.so
LoadModule env_module modules/mod_env.so
LoadModule expires_module modules/mod_expires.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule headers_module modules/mod_headers.so
LoadModule ident_module modules/mod_ident.so
LoadModule include_module modules/mod_include.so
LoadModule info_module modules/mod_info.so
LoadModule isapi_module modules/mod_isapi.so
LoadModule ldap_module modules/mod_ldap.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule mime_module modules/mod_mime.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule speling_module modules/mod_speling.so
LoadModule status_module modules/mod_status.so
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule ssl_module modules/mod_ssl.so
ServerAdmin admin@localhost
ServerName localhost:80
DocumentRoot "C:/xampp/htdocs"
Options FollowSymLinks
AllowOverride All
Order deny,allow
Deny from all
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Order allow,deny
Allow from all
DirectoryIndex index.php index.php4 index.php3 index.cgi index.pl index.html index.htm index.shtml index.phtml
Order allow,deny
Deny from all
ErrorLog logs/error.log
LogLevel warn
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
CustomLog logs/access.log common
ScriptAlias /cgi-bin/ "C:/xampp/cgi-bin/"
AllowOverride All
Options None
Order allow,deny
Allow from all
DefaultType text/plain
TypesConfig conf/mime.types
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
AddHandler cgi-script .cgi
AddType text/html .shtml
AddOutputFilter INCLUDES .shtml
EnableMMAP off
EnableSendfile off
Include conf/extra/httpd-xampp.conf
Include conf/extra/httpd-multilang-errordoc.conf
Include conf/extra/httpd-autoindex.conf
Include conf/extra/httpd-languages.conf
Include conf/extra/httpd-userdir.conf
Include conf/extra/httpd-info.conf
Include conf/extra/httpd-vhosts.conf
Include conf/extra/httpd-manual.conf
Include conf/extra/httpd-dav.conf
Include conf/extra/httpd-default.conf
Include conf/extra/httpd-ssl.conf
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
VHOSTS
c:/xampp/apache/conf/extra/httpd-vhosts.conf
NameVirtualHost *:80
DocumentRoot "c:\xampp\htdocs\myapp"
ServerName myapp.local
SetEnv APPLICATION_ENV "development"
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule !\.(js|ico|gif|jpg|png|css|php)$ \index.php
RewriteBase /
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
WINDOWS HOSTS
c:/windows/system32/drivers/etc/hosts
127.0.0.1 localhost
INDEX.PHP
c:/xampp/htdocs/myapp/index.php
(Really does start with < ?php and doesn’t end with ?>)
< ?php // Define path to application directory defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/application')); // Define application environment defined('APPLICATION_ENV') || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production')); // Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( realpath(APPLICATION_PATH . '/../library'), get_include_path(), ))); /** Zend_Application */ require_once 'Zend/Application.php'; // Create application, bootstrap, and run $application = new Zend_Application( APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini' ); require_once 'Zend/Mail.php'; $application->bootstrap()
->run();
PHPED PROJECT PROPERTIES
PROJECT
Root Directory: c:\xampp\htdocs\myapp Additional Directories: Source control: none
PUBLISHING
Account: Top publishing directory: Don't publish directories: CVS;.svn
MAPPING
HTTP mode (3rd party WEB server) Root URL: http://localhost Remote root directory: c:\xampp\htdocs\myapp
FILES
Default file to run: c:\xampp\htdocs\myapp\index.php Hide files: Hide directories: CVS;.svn
PARSER
CHECK Use Project-specific parser properties PARSER PROPERTIES Target PHP Version: 5.0 through 5.2 CHECK Support for short PHP tags < ? ?> UNCHECKED Parse PHP in CSS files UNCHECKED Support ASP style PHP Tags < % %> UNCHECKED Parse PHP in Javascript files
DEBUGGER
UNCHECKED Use Project-specific debugger settings
MAPPING
Remote Directory: c:\xampp\htdocs\myapp Local directory c:\xampp\htdocs\myapp URL: http://localhost Publishing Directory:
INTEGRATION
phpdoc_target_dir:
INCLUDES
Use what the debugger puts there
SECRET TO GETTING IT TO WORK IN PHPED
The default PhpED file is index.php. When you run the project in the debugger it will create a URL such as: http://localhost/index.php?DBGSESSID=403496131559100015@clienthost;d=1,p=0,c=1 And it will just keep recycling in the debugger, the call stack always going back to the first line of index.php. GET RID OF INDEX.PHP: Change the URL to http://localhost
Zend Server and XAMPP .htaccess mod_rewrite is on but ignored, creates 404′s
Virtual hosts require the rewrite engine be set in the conf rather than the .htaccess file. If you’re using a virtual host, put the mod rewrite commands in the virutal host settings.
Include the vhosts conf file by uncommenting c:\program files\zend\apache2\conf\httpd.conf:
Include conf/extra/httpd-vhosts.conf
Add a virtual host to conf/extra/httpd-vhosts.conf. Note that a conf RewriteCond requires a pre-pended slash where .htaccess doesn’t, so you are rewriting /index.php, not index.php.
NameVirtualHost *:80
<VirtualHost *:80>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ /index.php [NC,L]
DocumentRoot "c:\Program Files\Zend\Apache2\htdocs\yourapp"
ServerName yourapp.local
SetEnv APPLICATION_ENV development
<Directory "c:\program files\zend\apache2\htdocs\yourapp">
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
</Directory>
Add virtual host server to c:/windows/system32/drivers/etc/hosts:
127.0.0.1 yourapp.local
Restart apache
PhpEd Nusphere debugger gives “web server failed” debugging Zend framework project: dbg-wizard not found
To debug a Zend framework project set to run on a virtual host, use these settings:
- Web Server (Apache or another) used for development is located on this machine
- Document root: C:\zs\quickstart\public (i.e., the PUBLIC directory of your project)
- URL: http://quickstart.local/ (i.e, the virtual URL of your project)
- Project root directory: C:\zs\quickstart\public (i.e., the PUBLIC directory of your project)
A heavily corrected Windows XP XAMPP Zend Framework Quickstart Tutorial Revision
http://framework.zend.com/manual/en/learning.quickstart.intro.html
With many thanks to commenter alstanto on: 2010-04-07 22:04:18
Download Zend Framework 1.10.5 from:
http://downloads.zend.com/framework/1.10.5/ZendFramework-1.10.5.zip
Pre-Tutorial
- Extract to c:\ZendFramework-1.10.5
- Rename directory to c:\Zend
- Add to Environment Path:
;C:\Zend\bin;C:\Zend\library;C:\xampp\php
- Uncomment C:\xampp\apache\conf\httpd.conf
Include conf/extra/httpd-vhosts.conf
- In C:\xampp\apache\conf\extra\httpd-vhosts.conf add:
<VirtualHost *:80> DocumentRoot "c:\zs\quickstart\public" ServerName quickstart.local SetEnv APPLICATION_ENV "development" <Directory c:\zs\quickstart\public> DirectoryIndex index.php AllowOverride All Order allow,deny Allow from all </Directory> </VirtualHost> <VirtualHost *:80> DocumentRoot C:\xampp\htdocs ServerName localhost </VirtualHost>
- In C:\WINDOWS\system32\drivers\etc\hosts add:
127.0.0.1 quickstart.local
This means your tutorial files are accessed via http://quickstart.local
LoadModule rewrite_module modules/mod_rewrite.so
include_path = ".;C:\xampp\php\pear\;c:\Zend\library"
extension=php_pdo.dll extension=php_pdo_sqlite.dll
Reboot
START tutorial
http://framework.zend.com/manual/en/learning.quickstart.create-project.html
- Run zf command line tool:
start, run, cmd cd \ mkdir zs cd zs zf create project quickstart
- This is not in the tutorial: add a rewrite rule to public/.htaccess so that the file looks as follows:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]RewriteCond %{REQUEST_FILENAME} -l [OR]RewriteCond %{REQUEST_FILENAME} -dRewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
RewriteRule !\.(js|ico|txt|gif|jpg|png|css)$ index.php
- View welcome page
http://quickstart.local
CONTINUE tutorial
http://framework.zend.com/manual/en/learning.quickstart.create-layout.html
- Return to the cmd line at C:\zs\quickstart
zf enable layout
- Edit C:\zs\quickstart\application\BootStrap.php. Add this method to the Bootstrap class:
protected function _initDoctype() { $this->bootstrap('view'); $view = $this->getResource('view'); $view->doctype('XHTML1_STRICT'); } - Add line to C:\zs\quickstart\application\configs\application.ini, production section:
resources.view[] =
- Replace the contents of C:\zs\quickstart\application\layouts\scripts\layout.phtml with:
<!-- application/layouts/scripts/layout.phtml --> <?php echo $this->doctype() ?> <html xmlns="http://www.worg/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf- /> <title>Zend Framework Quickstart Application</title> <?php echo $this->headLink()->appendStylesheet('/css/global.css') ?> </head> <body> <div id="header" style="background-color: #EEEEEE; height: x;"> <div id="header-logo" style="float: left"> <b>ZF Quickstart Application</b> </div> <div id="header-navigation" style="float: right"> <a href="<?php echo $this->url( array('controller'=>'guestbook'), 'default', true) ?>">Guestbook</a> </div> </div> <?php echo $this->layout()->content ?> </body> </html> - View new layout, note guestbook is not yet hooked up:
http://quickstart.local
Continue tutorial
http://framework.zend.com/manual/en/learning.quickstart.create-model.html
- Tutorial commands will not work in Windows. Tutorial asks you to run in cmd c:\zs\quickstart:
zf configure db-adapter "adapter=PDO_SQLITE&dbname=APPLICATION_PATH '/../data/db/guestbook.db'" production
The tutorial would also have you put all three databases in the [production] section. Instead run these commands:
zf configure db-adapter "adapter=PDO_SQLITE&dbname=APPLICATION_PATH \"/../data/db/guestbook.db\"" production zf configure db-adapter "adapter=PDO_SQLITE&dbname=APPLICATION_PATH \"/../data/db/guestbook-testing.db\"" testing zf configure db-adapter "adapter=PDO_SQLITE&dbname=APPLICATION_PATH \"/../data/db/guestbook-dev.db\"" development
This is neither part of the tutorial NOR the project.
If you want to use MySql instead of Sqlite:
- In c:/xampp/php/php.ini, uncomment
extension=php_pdo_mysql.dll
- At cmd c:/zs/quickstart, run command (change to your dbname, host, username, password)
zf configure db-adapter "adapter=PDO_MYSQL&dbname=mydb&host=localhost&username=root&password production
- Restart Apache
- In localhost/phpmyadmin create database mydb
- Create the db directory in cmd at c:\zs\quickstart (you don’t do this for mysql):
mkdir data\db attrib -R data
- At this point the tutorial would have you create scripts/schema.sqlite.sql and other database files. The tutorial took you through creating data\db, so it should also mention that scripts needs to be created. In cmd at C:\zs\quickstart:
mkdir scripts
- Create c:/zs/quickstart/scripts/schema.sqlite.sql (for mysql name the file schema.mysql.sql)
-- scripts/schema.sqlite.sql -- -- You will need load your database schema with this SQL. CREATE TABLE guestbook ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, email VARCHAR(32) NOT NULL DEFAULT 'noemail@test.com', comment TEXT NULL, created DATETIME NOT NULL ); CREATE INDEX "id" ON "guestbook" ("id"); - Create c:/zs/quickstart/scripts/data.sqlite.sql (for mysql name the file data.mysql.sql)
-- scripts/data.sqlite.sql -- -- You can begin populating the database with the following SQL statements. INSERT INTO guestbook (email, comment, created) VALUES ('ralph.schindler@zend.com','Hello! Hope you enjoy this sample zf application!',DATETIME('NOW')); INSERT INTO guestbook (email, comment, created) VALUES('foo@bar.com','Baz baz baz, baz baz Baz baz baz - baz baz baz.',DATETIME('NOW')); - Create scripts/load.sqlite.php (for mysql name the file load.mysql.php and change all script references from sqlite to mysql). The tutorial does not include <?php and ?>. Add these.
<?php // scripts/load.sqlite.php /** * Script for creating and loading database */ // Initialize the application path and autoloading defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application')); set_include_path(implode(PATH_SEPARATOR, array( APPLICATION_PATH . '/../library', get_include_path(), ))); require_once 'Zend/Loader/Autoloader.php'; Zend_Loader_Autoloader::getInstance(); // Define some CLI options $getopt = new Zend_Console_Getopt(array( 'withdata|w' => 'Load database with sample data', 'env|e-s' => 'Application environment for which to create database (defaults to development)', 'help|h' => 'Help -- usage message', )); try { $getopt->parse(); } catch (Zend_Console_Getopt_Exception $e) { // Bad options passed: report usage echo $e->getUsageMessage(); return false; } // If help requested, report usage message if ($getopt->getOption('h')) { echo $getopt->getUsageMessage(); return true; } // Initialize values based on presence or absence of CLI options $withData = $getopt->getOption('w'); $env = $getopt->getOption('e'); defined('APPLICATION_ENV') || define('APPLICATION_ENV', (null === $env) ? 'development' : $env); // Initialize Zend_Application $application = new Zend_Application( APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini' ); // Initialize and retrieve DB resource $bootstrap = $application->getBootstrap(); $bootstrap->bootstrap('db'); $dbAdapter = $bootstrap->getResource('db'); // let the user know whats going on (we are actually creating a // database here) if ('testing' != APPLICATION_ENV) { echo 'Writing Database Guestbook in (control-c to cancel): ' . PHP_EOL; for ($x = 5; $x > 0; $x--) { echo $x . "\r"; sleep(1); } } // Check to see if we have a database file already $options = $bootstrap->getOption('resources'); $dbFile = $options['db']['params']['dbname']; if (file_exists($dbFile)) { unlink($dbFile); } // this block executes the actual statements that were loaded from // the schema file. try { $schemaSql = file_get_contents(dirname(__FILE__) . '/schema.sqlite.sql'); // use the connection directly to load sql in batches $dbAdapter->getConnection()->exec($schemaSql); chmod($dbFile, 0666); if ('testing' != APPLICATION_ENV) { echo PHP_EOL; echo 'Database Created'; echo PHP_EOL; } if ($withData) { $dataSql = file_get_contents(dirname(__FILE__) . '/data.sqlite.sql'); // use the connection directly to load sql in batches $dbAdapter->getConnection()->exec($dataSql); if ('testing' != APPLICATION_ENV) { echo 'Data Loaded.'; echo PHP_EOL; } } } catch (Exception $e) { echo 'AN ERROR HAS OCCURED:' . PHP_EOL; echo $e->getMessage() . PHP_EOL; return false; } // generally speaking, this script will be run from the command line return true; ?> - At the cmd c:\zs\quickstart
php scripts/load.sqlite.php --withdata
- At the cmd c:\zs\quickstart
zf create db-table Guestbook guestbook
- Create application/models/GuestbookMapper.php
<?php // application/models/GuestbookMapper.php class Application_Model_GuestbookMapper { public function save($model); public function find($id, $model); public function fetchAll(); } ?> - At the cmd c:\zs\quickstart
zf create model GuestbookMapper
- Replace contents of application/models/GuestbookMapper.php with:
// application/models/GuestbookMapper.php class Application_Model_GuestbookMapper { protected $_dbTable; public function setDbTable($dbTable) { if (is_string($dbTable)) { $dbTable = new $dbTable(); } if (!$dbTable instanceof Zend_Db_Table_Abstract) { throw new Exception('Invalid table data gateway provided'); } $this->_dbTable = $dbTable; return $this; } public function getDbTable() { if (null === $this->_dbTable) { $this->setDbTable('Application_Model_DbTable_Guestbook'); } return $this->_dbTable; } public function save(Application_Model_Guestbook $guestbook) { $data = array( 'email' => $guestbook->getEmail(), 'comment' => $guestbook->getComment(), 'created' => date('Y-m-d H:i:s'), ); if (null === ($id = $guestbook->getId())) { unset($data['id']); $this->getDbTable()->insert($data); } else { $this->getDbTable()->update($data, array('id = ?' => $id)); } } public function find($id, Application_Model_Guestbook $guestbook) { $result = $this->getDbTable()->find($id); if (0 == count($result)) { return; } $row = $result->current(); $guestbook->setId($row->id) ->setEmail($row->email) ->setComment($row->comment) ->setCreated($row->created); } public function fetchAll() { $resultSet = $this->getDbTable()->fetchAll(); $entries = array(); foreach ($resultSet as $row) { $entry = new Application_Model_Guestbook(); $entry->setId($row->id) ->setEmail($row->email) ->setComment($row->comment) ->setCreated($row->created); $entries[] = $entry; } return $entries; } } - At c:\zs\quickstart cmd
zf create model Guestbook
- Replace contents of application/models/Guestbook.php with:
// application/models/Guestbook.php class Application_Model_Guestbook { protected $_comment; protected $_created; protected $_email; protected $_id; public function __construct(array $options = null) { if (is_array($options)) { $this->setOptions($options); } } public function __set($name, $value) { $method = 'set' . $name; if (('mapper' == $name) || !method_exists($this, $method)) { throw new Exception('Invalid guestbook property'); } $this->$method($value); } public function __get($name) { $method = 'get' . $name; if (('mapper' == $name) || !method_exists($this, $method)) { throw new Exception('Invalid guestbook property'); } return $this->$method(); } public function setOptions(array $options) { $methods = get_class_methods($this); foreach ($options as $key => $value) { $method = 'set' . ucfirst($key); if (in_array($method, $methods)) { $this->$method($value); } } return $this; } public function setComment($text) { $this->_comment = (string) $text; return $this; } public function getComment() { return $this->_comment; } public function setEmail($email) { $this->_email = (string) $email; return $this; } public function getEmail() { return $this->_email; } public function setCreated($ts) { $this->_created = $ts; return $this; } public function getCreated() { return $this->_created; } public function setId($id) { $this->_id = (int) $id; return $this; } public function getId() { return $this->_id; } } - At cmd z:\zs\quickstart
zf create controller Guestbook
- Add these lines to c:\zs\quickstart\application\controllers\GuestbookController.php init method
$guestbook = new Application_Model_GuestbookMapper(); $this->view->entries = $guestbook->fetchAll();
So that GuestbookController.php indexAction now looks like this:
// application/controllers/GuestbookController.php public function indexAction() { $guestbook = new Application_Model_GuestbookMapper(); $this->view->entries = $guestbook->fetchAll(); } - Change out the contents of c:\zs\quickstart\application\views\scripts\guestbook\index.phtml with:
<!-- application/views/scripts/guestbook/index.phtml --> <p><a href="<?php echo $this->url( array( 'controller' => 'guestbook', 'action' => 'sign' ), 'default', true) ?>">Sign Our Guestbook</a></p> Guestbook Entries: <br /> <dl> <?php foreach ($this->entries as $entry): ?> <dt><?php echo $this->escape($entry->email) ?></dt> <dd><?php echo $this->escape($entry->comment) ?></dd> <?php endforeach ?> </dl>
- View the guest book
http://quickstart.local
Note that the sign guest book is not implemented yet
- At cmd c:\zs\quickstart
zf create form Guestbook
- Replace application/forms/Guestbook.php with:
(add <?php and ?> which are missing in tutorial)<?php // application/forms/Guestbook.php class Application_Form_Guestbook extends Zend_Form { public function init() { // Set the method for the display form to POST $this->setMethod('post'); // Add an email element $this->addElement('text', 'email', array( 'label' => 'Your email address:', 'required' => true, 'filters' => array('StringTrim'), 'validators' => array( 'EmailAddress', ) )); // Add the comment element $this->addElement('textarea', 'comment', array( 'label' => 'Please Comment:', 'required' => true, 'validators' => array( array('validator' => 'StringLength', 'options' => array(0, 20)) ) )); // Add a captcha $this->addElement('captcha', 'captcha', array( 'label' => 'Please enter the 5 letters displayed below:', 'required' => true, 'captcha' => array( 'captcha' => 'Figlet', 'wordLen' => 5, 'timeout' => 300 ) )); // Add the submit button $this->addElement('submit', 'submit', array( 'ignore' => true, 'label' => 'Sign Guestbook', )); // And finally add some CSRF protection $this->addElement('hash', 'csrf', array( 'ignore' => true, )); } } ?> - In c:\zs\quickstart cmd run
zf create action sign Guestbook
- Replace application/controllers/GuestbookController.php signAction() with:
public function signAction() { $request = $this->getRequest(); $form = new Application_Form_Guestbook(); if ($this->getRequest()->isPost()) { if ($form->isValid($request->getPost())) { $comment = new Application_Model_Guestbook($form->getValues()); $mapper = new Application_Model_GuestbookMapper(); $mapper->save($comment); return $this->_helper->redirector('index'); } } $this->view->form = $form; } - Replace application/views/scripts/guestbook/sign.phtml contents with:
<!-- application/views/scripts/guestbook/sign.phtml --> Please use the form below to sign our guestbook! <?php $this->form->setAction($this->url()); echo $this->form;
- View and add guestbook entries
http://quickstart.local
zf configure db-adapter "adapter=PDO_MYSQL&dbname=zipforce&host=localhost&username=root&password production
CONTINUE tutorial
http://framework.zend.com/manual/en/learning.quickstart.create-form.html