Filed Under (General) by Wenbert on 23-04-2008
Sometimes, I “mix” PHP variables with Javascript. For example, I have something like this:
function deletenote(notes_id)
{
if(!confirm("Delete note? You will not be able to undo this action."))
return false;
$.post("< ?=$this->baseUrl?>/notes/deletenote",{
skeedl_notes_id: notes_id
}, function(data){
$(‘#notes_id’+data).fadeOut();
});
}
Note the $this->baseUrl, I need it like that. The thing is, I have that code in my view file (.phtml - in Zend Framework, this is parsed like a normal PHP file). If I remove all the Javascript in my view file and place it in a .js file, the $this->baseUrl will not be parsed. To go around this, I create a hidden input element in my view file with $this->baseUrl echoed as the value. Like this:
// … in my .phtml file …
// rest of the php and html code goes here
< input type="hidden" id="base_url" value="<?=$this->baseUrl?>" />
// rest of the php and html code goes here
Then in my .js file (assuming that you have already included this file in your header, or somewhere else), I have something like this:
//This is using jQuery, but you can use document.getElementById(’base_url’).value if you like
function deletenote(notes_id)
{
if(!confirm("Delete note? You will not be able to undo this action."))
return false;
$.post($(‘base_url’).val()+"/notes/deletenote",{
skeedl_notes_id: notes_id
}, function(data){
$(‘#notes_id’+data).fadeOut();
});
}
What it does is that jQuery gets the value of the hidden form element. The value of this hidden form element is from a PHP Variable.
So there you go, nothing special. Just something that works and I just wanted to share.
Filed Under (General) by Wenbert on 02-02-2008
A few weeks back, someone sent me an email.
Hi,
We just posted an article “The Cheat Sheet Cheat Sheet: Top 100 Lists of Web Development Cheat Sheets “
( http://www.virtualhosting.com/blog/2008/the-cheat-sheet-cheat-sheet-top-100-lists-of-web-development-cheat-sheets/ )I thought I’d bring it to your attention just in case you think your readers would find it interesting.
Either way, thanks for your time!
Amy (snip-snip)
Filed Under (General) by Wenbert on 04-12-2007
From jansch.nl:
This is not the best way to escape data. The most important reason is security. addslashes can lure you into a false sense of security. As Chris Shiflett points out, there are situations that addslashes doesn’t escape.
Use mysql_real_escape_string instead.
Filed Under (General) by Wenbert on 25-11-2007
I have just completed (well almost - but it is now fully functional) my CMS (Content Managment System) using the Zend Framework. I’m calling it “Hamburger” - after the current project I am working on, WorldsGreatestHamburgers.com. I am excited to release this publicly, but I am still working on the Categories and User Management. For now, you can get a preview of the CMS here.
Filed Under (General) by Wenbert on 14-11-2007
I have been handling file uploads in most of my web applications. Sometimes, I store them in databases and sometimes I feel like storing them in directories. This post will not deal with uploading files, but rather downloading them. Basically, I used PHP’s readfile() function to read the file and then output it - with the headers set. So here goes…
< ?php class ResearchController extends Zend_Controller_Action
{
…rest of the code here…
function downloadFileAction()
{
$id = $this->getRequest()->getParam(‘id’);
$filename = $this->getRequest()->getParam(‘filename’);
$path = Zend_Registry::get(‘uploadDir’).$id.‘/’.$filename;
header(‘Content-Type: application/octet-stream’);
echo readfile ($path);
exit; //this is important! you will get a corrupted file if you do not put exit;
}
}
…rest of the code here…
uploadDir is not accessible through the URL. This is an instance of Zend_Registry which is coded inside the bootstrp file (the index.php in ZF). Let’s just say that it is located in /home/ekini/uploads. While the website is located at /home/ekini/public_html/. The reason for storing the files outside the publicly accessible directly is so that no body can access the file using the URL. For example, if you put your upload directory inside public_html, anyone can access it using this URL: http://www.mysite.com/uploads/confidential_file.pdf. You can avoid this by simply putting out anywhere outside the public_html directory.
In my view file, I would have something like this:
http://www.mysite.com/research/downloadFile/id/16/filename/HelloWorld.pdf
Where research is the controller, downloadFile is the action, id is the directory inside uploadDir which stores the file that is named: HelloWorld.pdf.
The post is pretty rough on the edges, but I hope you got the idea.
Filed Under (General) by Wenbert on 28-10-2007
It is Saturday night and it is raining like it hasn’t rained in weeks. So I decided to spend the night to work on my pet project: MyLyricsFinder.com.
It uses the Zend Framework. The latest addition tonight is Zend_Cache. I added the Top 10 Songs and Artist list in the frontpage - so caching it would make sense. Without the cache, every user that will visit the site will have to query the database. Getting the top 10 list from 200K+ rows is pretty heavy on the resources. Not to mention the overhead it will cause on the user’s side. So I came up with the code below:
//this code snippet is part of my indexAction() in my IndexController
//for the cache
$frontendOptions = array();
$frontendOptions[‘lifetime’] = 3600;
$frontendOptions[‘automatic_serialization’] = true;$backendOptions = array();
$backendOptions[‘cache_dir’] = Zend_Registry::get(‘cache_dir’);
// getting a Zend_Cache_Core object
$cache = Zend_Cache::factory(‘Core’, ‘File’, $frontendOptions, $backendOptions);
// see if a cache already exists:
if(!$result_pop_songs = $cache->load(‘pop_songs’)) {
//get most popular songs
$dbAdapter = Zend_Registry::get(‘dbAdapter’);
$sql = ‘SELECT
s.song_title,
s.song_slug,
s.song_counter,
at.artist_slug
FROM songs_table s
LEFT JOIN album_table al ON s.album_id=al.album_id
LEFT JOIN artist_table at ON al.artist_id=at.artist_id
WHERE s.song_counter>0 ORDER BY s.song_counter DESC LIMIT 10′;
$this->view->pop_songs = $dbAdapter->fetchAll($sql);
$cache->save($this->view->pop_songs, ‘pop_songs’);
} else {
// cache hit! shout so that we know
//echo "This one is from cache!\n\n";
$this->view->pop_songs = $result_pop_songs;
}
In addition to the Top 10 List in the frontpage, I have also cached the list of Artist per Letter and the List of Albums per Artist. I have reduced the number of database requests significantly - although I don’t know how much - I can tell the difference in load time with and without the cache.
Code Walkthough
$frontendOptions = array();
$frontendOptions[‘lifetime’] = 3600;
$frontendOptions[‘automatic_serialization’] = true;
$backendOptions = array();
$backendOptions[‘cache_dir’] = Zend_Registry:: get(‘cache_dir’);
$cache = Zend_Cache:: factory(‘Core’, ‘File’, $frontendOptions, $backendOptions);
This part of the code sets up the Zend_Cache. Most likely, yours will be similar to this. Except for the line with the get(’cache_dir’). I have set up Zend_Registry::get(’cache_dir’) in my Bootstrap file to “../tmp/”
if(!$result_pop_songs = $cache->load(‘pop_songs’)) {
The line above checks if a cache for ‘pop_songs’ already exists. If not, then it will query the database with the code below:
$dbAdapter = Zend_Registry:: get(‘dbAdapter’);
$sql = ‘SELECT
s.song_title,
s.song_slug,
s.song_counter,
at.artist_slug
FROM songs_table s
LEFT JOIN album_table al ON s.album_id=al.album_id
LEFT JOIN artist_table at ON al.artist_id=at.artist_id
WHERE s.song_counter>0 ORDER BY s.song_counter DESC LIMIT 10′;
$this->view->pop_songs = $dbAdapter->fetchAll($sql);
$cache->save($this->view->pop_songs, ‘pop_songs’);
The last line will save the query into the cache. So the next time a user will come, the ‘pop_songs’ cache will already exist in the cache and the code below is executed:
$this->view->pop_songs = $result_pop_songs;
Filed Under (General) by Wenbert on 16-10-2007
An article where a couple of guys decided to use Ruby on Rails instead of Java and Google Web Toolkit. I would encourage everyone who is learning RoR to read the entire article. Don’t skip the last part of the article - it should give us RoR newbies a heads-up.
Snip. Snip. Snip.
We had a great introductory ride on Ruby on Rails. We didn’t know Ruby or Rails at all before we started, and we were able to launch a pretty sophisticated web app in a short amount of time. But of course, as with all things, there were mistakes we had to make — mistakes that we would rather avoid in the future.
Design First in HTML + JS
Our biggest mistake: we didn’t complete our interface design before we started programming in rails (Getting Real did teach us to Design Interface First). This was completely understandable, because we didn’t really know what (design & interface-wise) was really hard, versus what was easy to implement in rails. We had to play around with the programming and implementation before we completely designed our app. If we hadn’t, we might have designed our way into an impossibly difficult interface to implement in rails.
But now we know what rails can and can’t do. And we really can’t stress this enough - WE WILL DESIGN OUR INTERFACE FIRST - COMPLETELY! This means we will sit down together and draw every page out on paper together (we like to do this over meals). Once the paper mockups are in order, we will then create full HTML mockups with javascript. Once we settle on the user interface, we’ll go back and “fill in the blanks” with server side code. The beauty is that in Rails, it really is fill-in-the-blanks, and it makes design first a breeze.
Good Javascript Libraries
There were a few painful points that we thought took a long time when writing our app. One of them was surely javascript. Although prototype and scriptaculous are a good start (particularly because there are great helpers to interface with them in rails), there is so far to go in this department. Before we try to write a lot of javascript, we’ll be sure to write additional helpers between rails and our JS code to make it drop-dead-easy to create features.
Use Fixtures Sparingly
When we started testing fixtures provided a way to quickly setup test data. However as our models became more complex and the relationships between them more involved, maintaining fixture data quickly became a headache. Going forward we will be using Mocha to create mock objects for our tests where there is a need to setup relationships between models.
Caching
When we started coding we had discussed implementing caching, but as deadlines approached we kept putting it off. Sure enough when the Beta launched, we didn’t take advantage of caching. In the future we know that we will need to implement caching, but it will probably require a good bit of refactoring to be effective.
Grab the article here.
Filed Under (General) by Wenbert on 16-10-2007
A must read for PHP Programmers. Here is the first half:
- If a method can be static, declare it static. Speed improvement is by a factor of 4.
- echo is faster than print.
- Set the maxvalue for your for-loops before and not in the loop.
- Unset your variables to free memory, especially large arrays.
- Avoid magic like __get, __set, __autoload
- require_once() is expensive
- Use full paths in includes and requires, less time spent on resolving the OS paths.
- If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time()
- See if you can use strncasecmp, strpbrk and stripos instead of regex
- str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4
- If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.
- Error suppression with @ is very slow.
- $row[’id’] is 7 times faster than $row[id]
- Error messages are expensive
- Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time.
- Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
- Incrementing a global variable is 2 times slow than a local var.
- Incrementing a object property (eg. $this->prop++) is 3 times slower than a local variable.
- Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
- Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
For the other half, go here.
Filed Under (General) by Wenbert on 14-10-2007
This article was posted at IBM developerWorks a few days ago - I don’t know how I missed it. The article gets you started on three of the most popular PHP MVC Frameworks. Surprisingly, Code Igniter, which is my second option next to Zend Framework is not included in the article. Definitely as must read for anyone who is into MVC Development.
Here is a snippet:
There are several frameworks available for nearly every language. Selecting the right one for your needs can be somewhat difficult, especially if you haven’t used any of them before. While advice and opinions from colleagues and trusty developerWorks authors can be helpful in this area, there is really only one guiding principle that should be followed when selecting any framework: A framework is only as good as the amount of time and effort it saves everyone. A framework is no good if it works well for you but causes a significant increase in support calls. A framework is no good if it is easy to support, but hinders rather than assists your development. A framework is useless if it is elegant, but causes support and development issues.
When selecting a framework for your project, consider everyone involved, from the top down, and when you evaluate the framework, keep the impact to other parties in mind.
When you consider adopting a framework, look at your application closely and ask yourself it if needs a framework. A framework isn’t a necessity. Enterprise applications will continue to be written without the use of frameworks. Will a framework help you with the project? Will it save everyone time and effort? Will your application perform better on a framework? Will it provide the stability you are lacking? If the answer to any of these questions is yes, you should look to adopt a framework. If the answer to all of these questions is no, a framework will only complicate matters.
Unfortunately, size and scope restraints do not allow for a comprehensive coverage of all available PHP frameworks. This series focuses on three frameworks:
- Zend Framework
- symfony
- CakePHP
These were selected based on a variety of factors, but might be best classified as “The One Your Boss Knows About,” “The One Someone Else Already Installed,” and “The One They’ve Been Talking About.” I encourage you to research CodeIgniter, Seagull, Web Application Component Toolkit (WACT), PRADO, Zoop, PHP on Trax, or any of the many other PHP frameworks available. Framework selection is very much a personal choice, much like selecting a language in which to code. This series isn’t going to tell you which framework is better, or worse, than the others. Where a framework does something well, it will be called out. Where a framework seems unwieldy, this will be called out, as well. Even if we are not comprehensive in our coverage of the myriad frameworks, the approach we take will help you weight the strengths and weaknesses of other frameworks. You need to form your own opinions about the frameworks being examined, which ones you like, and what you decide to pursue.
The Zend Framework
Everyone knows Zend — “The PHP Company.” When you download and install PHP, you’re downloading it from Zend and have been since around V3. In addition to distributing PHP, Zend Technologies has offered a wide range of PHP support technologies over the years. It should be no surprise that Zend offers a framework for PHP — a popular one at 2 million downloads to date. If your boss has heard of a PHP framework, the Zend Framework is likely to be the one.
symfony
Sponsored by Sensio, symfony “aims to speed up the creation and maintenance of Web applications, and to replace the repetitive coding tasks by power, control and pleasure.” The symfony framework has been used worldwide in a number of enterprise-level applications, perhaps most notably Askeet and Yahoo! Bookmarks. Odds are that if someone you know has installed, used, or played around with a PHP framework, that framework was symfony.
CakePHP
Borrowing heavily from Ruby on Rails, CakePHP aims to bring simplicity and scalability to PHP frameworks. Consistently recognized as a top PHP framework, CakePHP was recently selected as the core around which V5 of the Mambo Content Management System. Driven by a strong community and a rapidly growing user base, CakePHP’s popularity is growing steadily. If you’ve overheard a conversation about PHP frameworks, that conversation was probably about CakePHP.
Click here for the entire article.
Filed Under (General) by Wenbert on 10-10-2007
Last October 8, Apache Friends released new versions of XAMMP for Windows, Linux and Mac OS X. I use XAMMP on Windows, but for Mac OS X, I use MAMP - the Mac OS X release of XAMMP is still in its early stages.
They have updated the following:
- Apache to 2.2.6
- PHP to 5.2.4
- phpMyAdmin to 2.11.1
Click here for XAMMP.
|
|