mariano iglesias
mariano iglesias
July 2009
Mon Tue Wed Thu Fri Sat Sun
 << <   > >>
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31    
Search
XML Feeds
04 28 09
$entry->categorize('Programming, PHP, CakePHP'); | $entry->author('mariano.iglesias'); | $post->words(672);

With the release of CakePHP 1.2 a whole set of new features were made available to us bakers. One of those features is custom find types, which is one of the coolest things that ever happened since I realized I was cooler than Maverick.

I'm not gonna go through custom find types, you can find more info about them at Matt's blog, or at this article written by someone whose name I think I've heard somewhere. What I'm going to talk about is how to mix your custom find types with pagination, without having to use paginate and paginateCount in your models.

So let's first start by building yet another posts table, and inserting some records:

Code:

CREATE TABLE `posts`(
  `id` INT NOT NULL AUTO_INCREMENT,
  `title` VARCHAR(255) NOT NULL,
  `body` TEXT NOT NULL,
  `published` TINYINT(1) NOT NULL default 0,
  `created` DATETIME,
  `modified` DATETIME,
  PRIMARY KEY(`id`)
);
 
INSERT INTO `posts`(`title`, `body`, `published`, `created`, `modified`) VALUES
  ('Post 1', 'Body for Post 1', 1, NOW(), NOW()),
  ('Post 2', 'Body for Post 2', 0, NOW(), NOW()),
  ('Post 3', 'Body for Post 3', 0, NOW(), NOW()),
  ('Post 4', 'Body for Post 4', 1, NOW(), NOW()),
  ('Post 5', 'Body for Post 5', 1, NOW(), NOW()),
  ('Post 6', 'Body for Post 6', 0, NOW(), NOW()),
  ('Post 7', 'Body for Post 7', 1, NOW(), NOW()),
  ('Post 8', 'Body for Post 8', 1, NOW(), NOW()),
  ('Post 9', 'Body for Post 9', 1, NOW(), NOW());

Now let's assume we want a find type called published to fetch only the published posts, and that we also want to be able to paginate using this find type. We will be approaching this through a generic approach, something that can be used throughout all our models. With this in mind, let's first introduce a model based member variable called $_types, where we define the specific needs of each custom find type. Therefore, that variable will hold what we need as conditions, order, etc. for each custom find type. So let's build our Post model:

PHP:

<?php
class Post extends AppModel {
    public $name 'Post';
    protected $_types array(
        'published' => array(
            'conditions' => array('Post.published' => 1),
            'order' => array('Post.created' => 'desc')
        )
    );
}
?>

As you can see, we define options for each find type as if we would be calling find() directly. So with the above, instead of doing:

PHP:

$posts $this->Post->find('all'array(
    'conditions' => array('Post.published' => 1),
    'order' => array('Post.created' => 'desc')
));

We can now do:

PHP:

$posts $this->Post->find('published');

Now, what if we wanted to paginate with the above custom find type? Just as we set pagination parameters through the controller member variable $paginate, we can specify which find type pagination we'll use. We do so by specifying the find type in the index 0 of the pagination settings. Like so:

PHP:

$this->paginate['Post'] = array(
    'published',
    'limit' => 10
);
 
$posts $this->paginate('Post');

Easy, huh? When this is specified, paginate() does the following:

  1. It issues a find('count') on the Post model, specifying the custom find type (published) in the $options array, through an option named type. Therefore, we can use $options['type'] when our model is about to do the count to use the given options for our custom find type.
  2. It fetches the records by calling find() with the custom find type, find('published') in our example.

So where's that sexy code? Add the following in your AppModel, making the above available for all our models.

PHP:

<?php
class AppModel extends Model {
    public function find($type$options array()) {
        if (!empty($this->_types)) {
            $types array_keys($this->_types);
            $type = (is_string($type) ? $type null);
            if (!empty($type)) {
                if (($type == 'count' && !empty($options['type']) && in_array($options['type'], $types)) || in_array($type$types)) {
                    $options Set::merge(
                        $this->_types[($type == 'count' $options['type'] : $type)],
                        array_diff_key($optionsarray('type'=>true))
                    );
                }
                if (in_array($type$types)) {
                    $type = (!empty($this->_types[$type]['type']) ? $this->_types[$type]['type'] : 'all');
                }
            }
        }
        return parent::find($type$options);
    }
}
?>

Now ain't CakePHP great? Don't tell me, tell everyone at CakeFest #3.

$post->read(); | $feedbacks->add(); | $post->views(16639);
03 23 09
$entry->categorize('Business, Programming, PHP, CakePHP'); | $entry->author('mariano.iglesias'); | $post->words(179);

What better place to talk CakePHP than the world's beer nation? That was the question that made the CakePHP Team decide CakeFest third edition should be located in Berlin, Germany. Just as Buenos Aires was the meat fest, I hereby predict that this will be the Beer Fest.

Let's face it, your code gets better when you use CakePHP. So attending the official CakePHP gathering where all Core Developers and prominent community members go to share their knowledge is an offer you should not ignore. Add awesome beer and guaranteed fun to that recipe, and you would be insane not to join us.

So what are you waiting for? Go and get your CakeFest ticket as soon as possible, you don't want to be left behind! If you have a company, or you are a regular Baker just wanting to show your love back to the project, do not hesitate to sign up for the sponsorship packages. Also help us spread the word by placing these CakeFest badges in your site, and you may even get a free ticket!

$post->read(); | $feedbacks->add(); | $post->views(7876);
02 28 09
$entry->categorize('Programming, PHP'); | $entry->author('mariano.iglesias'); | $post->words(306);

Today I noticed my MySQL partition was taking over 86 GB of the available 120 GB. So I got worried and I wrote this little script to tell me how much space each DB I have is taking:

PHP:

<?php
 
function format($size) {
    $unit 'B';
    $units array(
        'GB' => 1024 1024 1024
        'MB' => 1024 1024
        'KB' => 1024
    );
 
    foreach($units as $currentUnit => $value) {
        if ($size $value) {
            $size /= $value;
            $unit $currentUnit;
            break;
        }
    }
            
    return number_format($size1) . ' ' $unit;
}
 
$settings array(
    'host' => 'localhost'
    'user' => 'root'
    'password' => 'password'
);
 
$databases array();
 
mysql_connect($settings['host'], $settings['user'], $settings['password']);
 
$result mysql_query('show databases');
while($row mysql_fetch_array($result)) {
    $databases[] = $row['Database'];
}
 
foreach($databases as $database) {
    $sizes[$database] = 0;
 
    mysql_select_db($database);
    $result mysql_query('show table status');
    while($row mysql_fetch_array($result)) {
        $sizes[$database] += $row['Data_length'] + $row['Index_length'];
    }
}
 
mysql_close();
 
foreach($sizes as $database => $size) {
    echo $database ' = ' format($size) . '<br />';
}
 
echo '<br />TOTAL: ' format(array_sum($sizes));
 
?>

When I ran it, I saw all my DBs where taking a total of 10.8 GB, much less than the 86 GB occupied in the partition. So it hit me, it has to be the binary logs, a set of files that store log events (more about them here). Indeed, if you would list the contents of /var/lib/mysql I would find a ton of .bin files, a lot of them as old as from 2007. Therefore, I realized I had to flush the logs.

In order to flush the binary logs, I logged in to the MySQL console as an administrator, and issued (if you are on a server with replication, you want to purge the binary logs instead):

Code:

FLUSH LOGS;
RESET MASTER;

After doing so, the MySQL partition is now taking a total of 12 GB. Much better!

$post->read(); | $feedbacks->show(1); | $post->views(5315);
02 07 09
$entry->categorize('Programming, C++'); | $entry->author('mariano.iglesias'); | $post->words(468);

As a true programmer, I need fun projects to stay alive. Don't get me wrong, my client work fulfills me, and eventhough I've been slacking lately in keeping up with its workload, CakePHP is also a lot of fun. However, true programmers are always looking for a fun project, one they can call their own. Meet CLAPP, a C++ MVC Web Framework.

I am not even close to finishing it, but so far I'm having LOTS of fun. What is amazing is that missing only the M in MVC (the database abstraction layer), CLAPP's performance is already astonishing. Running as FastCGI, it outperforms the most basic PHP file by a ratio of 1000%. Amazing.

So what am I looking to gain from this? Nothing, just having fun going back to my absolute favourite language: C++. In the meantime, I get to play with speed comparisons, which gets particularly interesting as I enable more stuff in the framework. My ideal goal is to include a lot of the you-just-have-to-have-this kind of things available on real, serious frameworks such as CakePHP. This doesn't mean that I will hereon start developing every web application in C++, that would just be dumb (if you are asking why, then that's because you haven't given CakePHP a try). It does mean, however, that I'll be posting about CLAPP every now and then.

To calm your expectations, here's a very, VERY small preview of the Dispatcher, which is directly attached to every controller:

Code:

#ifndef __CLAPP_DISPATCHER_HPP
#define __CLAPP_DISPATCHER_HPP
 
#include <clapp/cgi_stream.h>
#include <clapp/controller.h>
 
namespace clapp {
  template <class C>
  class Dispatcher {
    public:
      Dispatcher();
      ~Dispatcher();
      void dispatch();
 
    private:
#ifdef CLAPP_WITH_FASTCGI
      CgiStreamFastCgi * cgiStream;
#else
      CgiStream * cgiStream;
#endif
 
      void execute();
  };
}
 
template <class C>
clapp::Dispatcher<C>::Dispatcher() {
#ifdef CLAPP_WITH_FASTCGI
  this->cgiStream = new CgiStreamFastCgi();
#else
  this->cgiStream = new CgiStream();
#endif
}
 
template <class C>
clapp::Dispatcher<C>::~Dispatcher() {
  delete this->cgiStream;
}
 
template <class C>
void clapp::Dispatcher<C>::dispatch() {
#ifdef CLAPP_WITH_FASTCGI
  FCGX_Request request;
 
  FCGX_Init();
  FCGX_InitRequest(&request, 0, 0);
 
  while (FCGX_Accept_r(&request) == 0) {
    this->cgiStream->setRequest(request);
    this->execute();
    FCGX_Finish_r(&request);
  }
#else
  this->execute();
#endif
}
 
template <class C>
void clapp::Dispatcher<C>::execute() {
  C *controller = NULL;
 
  try {
    controller = new C();
 
    controller->setStream(this->cgiStream);
    controller->dispatch();
 
    delete controller;
  } catch(...) {
    if (controller != NULL) {
      delete controller;
    }
    throw;
  }
}
 
#endif

As you can guess from the source code, CLAPP can produce FastCGIs and regular CGIs. It uses ClearSilver for its view / layout templates, the FastCGI development kit (when FastCGI mode is enabled), and GNU cgicc as a CGI / FastCGI input wrapper. More news coming soon!

$post->read(); | $feedbacks->show(9); | $post->views(5455);
01 07 09
$entry->categorize('General, Ubuntu'); | $entry->author('mariano.iglesias'); | $post->words(591);

An interesting meme, I was tagged by Jeff Loiselle

  1. I once worked a full day serving beverages and hamburguers to a lot of people who were attending the agricultural exposition at La Rural. The issue was that out of every burger / soda we served, me and my friends would get one for ourselves. Not too productive.
  2. I can't sleep without a fan. I'm not kidding. Even if it's freezing, I would turn on the heat and still power on the fan. Just two days ago (I'm currently on vacations at a beach location south of BA), I had to buy a fan since the house I rent doesn't have one.
  3. I spent almost two years helping out local Rock / Reggae bands, including Todos Tus Muertos & Actitud Maria Marta. I started there because I faxed the manager of AMM telling him if he wanted to build a website. I think this was 1996 or something. Needless to say it was an interesting experience.
  4. I don't know how to drive, nor I can't because of an eye condition. In reality, they would give me the license if I wanted to, but I firmly believe I would be a danger to other drivers (even in Argentina, where drivers suck big time.)
  5. I absolutely hate politicians. With strong passion. I mean, seriously, if you are a politician, get the hell out of my way. I would tap dance on your ass if you don't.
  6. When I was on my last year of high school, I stopped going to class and instead would spend my time at the school bar. I ended up not going for over 7 months to class, so obviously I had to take a test in March for every subject (I think we had over 20), otherwise I wouldn't graduate. Since I didn't tell my parents what I did, they only thought I had to take just one test, for one class. I had to take them all *while* I was taking the exams to enter University. Somehow it all worked out, and I managed to pass those over 20 exams for high school and 4 university subjects in less than a month. Crazy.
  7. I absolutely love the new Guns N' Roses album, Chinese Democracy. I haven't bought a music CD since 1993, but I decided to buy this one. Totally worth it. If you don't think so, you are clueless about rock.

Tagees:

  • Clauz: the coolest person to have near you
  • Tim Koschützki: someone who needs help figuring out how to play soccer and not cut his leg in the process
  • Chris Hartjes: one of the coolest canucks I've ever met. He gets grumpy though.
  • Martín Bavio: a fellow baker from argentina, who knows a thing or two about design
  • Mark Story: the other awesome canuck, this one is almost the opposite of the grumpy one: he's strong with the force, since he never seems to loose his coolness
  • Lorena Iglesias: my fellow sister, a prolific writer (if you don't know spanish, she's worth the trouble to learn it)
  • Dennis Hennen: someone who I've been working with for a long time now, so I happen to know him quite well

Here are the MEME rules:

  • Link your original tagger(s), and list these rules on your blog.
  • Share seven facts about yourself in the post — some random, some weird.
  • Tag seven people at the end of your post by leaving their names and the links to their blogs.
  • Let them know they've been tagged by leaving a comment on their blogs and/or Twitter.
$post->read(); | $feedbacks->show(4); | $post->views(8012);
11 11 08

$entry->title('Book meme');

$entry->categorize('General, Ubuntu'); | $entry->author('mariano.iglesias'); | $post->words(66);

Picking up the meme from jono and matthew, here's my meme:

"a state of emergency became the rule" - The Dachau Concentration Camp, 1933 to 1945

  1. Grab the nearest book.
  2. Open it to page 56.
  3. Find the fifth sentence.
  4. Post the text of the sentence in your journal along with these instructions.
  5. Don’t dig for your favorite book, the cool book, or the intellectual one: pick the CLOSEST.
$post->read(); | $feedbacks->show(2); | $post->views(13492);
08 29 08
$entry->categorize('Programming, Ubuntu'); | $entry->author('mariano.iglesias'); | $post->words(32);

Wanna test your box performance, both its hard disk and memory? Try setting up a +370 table database, and then build a huge MySQL update file. Run it and get something like this:

$post->read(); | $feedbacks->show(7); | $post->views(27066);
08 11 08

$entry->title('Firefox is a hungry mother!');

$entry->categorize('Linux, Ubuntu'); | $entry->author('mariano.iglesias'); | $post->words(145);

Here I'm working with my humble Dual Processor, 2 GB RAM running Ubuntu 8.04.1, AMD64 edition. I was talking to a colleague / friend of mine and he told me that he (with his 7 GB RAM on a Mac OS) has his firefox eating some 750 MB. So I decided to see how much memory was firefox eating on my box. I run this command:

Code:

ps -C "firefox" -o pid=,vsz=,rss= | awk '{ printf "PID: %d, Virtual: %-.2f MB, Resources: %-.2f MB\n", $1, $2 / 1024, $3 / 1024 }'

And I got:

Code:

PID: 6223, Virtual: 778.06 MB, Resources: 403.70 MB

And I had just a couple of tabs open. So I said, ok, let's start fresh. Here's the same command with a firefox with just an about:blank, having just started up:

Code:

PID: 9139, Virtual: 462.02 MB, Resources: 56.34 MB

Nice to see resources drop, but Virtual is still at over 450 MB. Why oh why are you so hungry, dear firefox?

$post->read(); | $feedbacks->show(9); | $post->views(9702);