Getting HMVC to play nicely with deeply nested config files in Sparks

I was recently debugging an issue with Codeigniter Payments and HMVC. The issue was that config files were not being loaded if they were deeply nested – for example:

config/payments/my_gateway.php

The MX_Config path explodes the filepath provided on forward slashes, so if you do anything other than this->load->config(‘whatever’), the file you want won’t get loaded, since only the last segment will be sent to the CI_Config class.

I was able to implement a workaround by modifying the MX_Config class, and by passing TRUE as the third param when I loaded a config file in a spark (this asks the config loader to fail gracefully, returning FALSE when a config file isn’t found instead of using the show_error helper).

Alternatively, you can pass the
To MX_Config, replace the load function with:

public function load($file = ‘config’, $use_sections = FALSE, $fail_gracefully = FALSE, $_module = ”) {
$original_file = $file;
if (in_array($file, $this->is_loaded, TRUE)) return $this->item($file);

$_module OR $_module = CI::$APP->router->fetch_module();
list($path, $file) = Modules::find($file, $_module, ‘config/’);

if ($path === FALSE) {
$try1 = parent::load($file, $use_sections, $fail_gracefully);
if($try1) return $this->item($file);

$try2 = parent::load($original_file, $use_sections, $fail_gracefully);
if($try2) return $this->item($original_file);
}

if ($config = Modules::load_file($file, $path, ‘config’)) {
/* reference to the config array */
$current_config =& $this->config;

if ($use_sections === TRUE) {

if (isset($current_config[$file])) {
$current_config[$file] = array_merge($current_config[$file], $config);
} else {
$current_config[$file] = $config;
}

} else {
$current_config = array_merge($current_config, $config);
}
$this->is_loaded[] = $file;
unset($config);
return $this->item($file);
}
}

This tries the original path if the config file isn’t found at the reformatted path. Kind of a hack, I know – but I couldn’t find a more elegant way around this. Any suggestions are appreciated – but if you just need it to work – I hope this helps.

Posted in CodeIgniter, PHP, Programming | Leave a comment

Дом Водка – My Last Night on the Black Sea

I lived in a little village on the black sea for about 3 months in 2010, staying with a wonderful couple whom I had the great fortune of befriending. The village was at one time an old Soviet military base that while still somewhat active (though controlled by the Ukranian government now), is now pretty relaxed. The village used to be available to only Soviet soldiers, but after the Cold War ended was opened up to the general public. Now, it is a sleepy resort town, mostly full of good hearted people who generally spend their time preparing for the coming tourist season when the nightclubs on the pier open and the hotels and vacation rentals fill up. Most seemed to spend their spare time catching fish, meeting friends at the local pub and relaxing. Living in this village was like stepping back in time – a place where 70s model Ladas (a polish made, box-like car) line the streets and where one can find everything he needs from the small shopkeeper and the weathered farmer at the market. In this village, there were no chain stores, statues of Soviet war heroes lining the streets, and kindly Babushkas who created every delectable piece of Ukranian and Russian foodstuffs one could ever hope to chance upon. Needless to say, despite the long commute to the city, I grew quite fond of this place, and quite enjoyed my time there.

I was certainly an oddity in this little seaside village. Several times a week I would run 5-10 miles and sometimes more – through the village and up the beach, down the unpaved, criss-crossing backstreets, through the forest and the park. There were few runners here, and on top of the fact that I spoke really horrible Russian – I soon developed quite a reputation. As my friend would tell me – “You are famous here, Calvin.” At first, people just stared, but over time – and as my Russian improved – the village folk began to take a more direct interest in me. The good people I bought my food from (and oh, what wonderful food it was) slowly began to initiate conversations with me, the girls on the bus began to to ask me what I was doing here, and the “gangs” of teenage boys began to corner me and ask me to drink a beer with them, take a photo, say something in English, or all three at once.

In the middle of this village, and across from the Lenin statue, was a lone supermarket – and certainly not your average supermarket. This supermarket consisted of 4 rows of Vodka, 2 of beer, and 4 of canned foods, rice, buckwheat, and other staples – and of course – a bit of produce, meat and dairy. This layout was pretty typical for a small Ukranian supermarket. What was not typical was the night club and “hotel” upstairs.

One day, luckily my last day there, I was buying Hurman (hoor-man) at the supermarket – which is basically a persimmon twice the size of your fist (looks like a persimmon, tastes like a persimmon – but freaking huge). While I was checking out, a man walks up to me and says in very broken English, “Boss want meet you.”

“Ok?”

In Russian… “Please, follow me.”

Half from curiosity, and half from not feeling this was an offer I should refuse, I followed the man to the back of the supermarket and into a room filled with computers. The man who occupied the room wore Italian shoes, tight jeans, and a black leather jacket. He was smoking a cigarette and looked to be about 40.

In Russian…

“Hello, I am boss. My name is (we’ll call him Vladimir). I have hear of you – they say you computer guy. This is good, because I am need server administrator. Do you want job?”

Surprised and certainly amused, I kindly declined, introduced myself, and told him how much I enjoyed the Hurman. Assuming I must have misunderstood him, he responds,

“Ok, see man, my wife teacher English. You talk her – you understand she say. Please, one moment.”

He frantically dials a number, briefly explains the situation to his wife, and hands me the cell phone. A woman speaking in understandable English asks me “Do you want job as server administrator? My husband want hire you. He pay 400 hryvna per week (about $50).”

“No, no. Thank you, I have job.” I kindly thank her for her help and hand the phone back to Vladimir, who is still slightly bewildered but now seems to understand that I don’t see this as a stellar, upward trending career move.

In Russian… “Ok, ok,” he rationalizes. “You not want job. I am see. We be friends then, is good?”

“Sure!” I shrugged.

“Ok, please, follow me, friends drink together.”

“No, no, I don’t drink” I explained.

“Oh, please, just a taste, I want show you something. This good Vodka, DOME VODKA (House Vodka). Germans leave in WW2. This Vodka not for customer – only friend drink.”

I told him, “Ok, please, show me what you wish.”

The man leads me upstairs to a small “hotel” and proudly shows me his 8 or so rooms.

“You see? This is hotel.” ..and opening the door to the night club… “And this is club!”

Still gleaming, by this time I’ve noticed that he’s already been sipping the Dome Vodka a bit. He disappears behind the bar for a moment, and returns with a huge, clear jar of Vodka. When he opened it, it was obvious that this was indeed very good Vodka.

You should know that when Ukranians / Russians drink Vodka, they don’t drink from those pesky things we Westerners call shot glasses. They pound mason jars (exaggerating just a bit, but not much) full of the stuff – one after another – and usually eat dried fish or raw pork fat (called Sala). He set my own mason jar in front of me and proclaimed generously “Ok, now we are drink.”

As I pretended to sip my Vodka, Vladimir proceeded to slowly recount the executive summary of pretty much his entire life. He spoke in Russian, so I only caught half of it, but I caught enough to get a good feel for who the guy was. He explained how he had come to the village after an exciting career as a captain in the KGB, and had settled into the quiet life of a local mafia boss. I just kept nodding my head, seeming interested, and assuring him that Americans did not feel animosity towards ex-KGB officers. After half an hour or so of this he was nearing a table-checking state (when you’re drunk enough that your head sways back and forth with your speech and you near headbutting the table), and seemed to have built up quite a liking for me. He said:

“Ah, you are good American. I am like you. Listen, I make you an offer, friend. First, if you need ride, or to be ride to airport, I arrange a Porsche to get you. And if you need girl – just ask me. Also, I am man who solve problem. If you have problem here, you let me know, and mans with machine gun come in car and solve problem.”

In one slurred sentence, he had just crossed the threshold from amicable ex-Soviet Agent with interesting stories to “guy who solve problem with machine gun.” It was time to go. After spending a few minutes looking at the various photos hanging on the wall of the club and complimenting Vladimir on his fine work putting all of this together, I explained that it was now very late, and I must get up very early to catch the bus. After insisting that he arrange a car for me, and me very politely refusing, he finally agrees to having 2 of the supermarket employees escort me across the parking lot. The supermarket employees walked with me across the parking lot, explained that boss is very drunk tonight, and wished me a pleasant evening.

I haven’t been back that supermarket since, but if I ever do find myself there again, I’ll probably avoid speaking and count myself lucky for having a somewhat impressive beard on my last visit. ..and hey, it could have just been the House Vodka talking.

Posted in Adventure, Travel | 1 Comment

Good Charity, Bad Charity – The Chicken Story and How it Changed My Life

I spent about a year in Hawaii when I was 18/19. Lots of fun times, with a couple life changing experiences mixed in with some time that otherwise went by way too quickly.

One of those I felt like recounting today.

The Chicken Story

In Hawaii, there are chickens everywhere. The locals told me that the English had introduced them when they landed, and because there are no predators, they flourished. Oahu, the big Island, and Kauai (all islands I visited) – there are chickens *everywhere.* The chicken problem is so big that in Oahu, the Honolulu county government offers a handsome salary to anyone who volunteers to round them up and educate those who domesticate them on how to keep their roosters quiet. In 2007, that salary was $40k. In 2008, it was increased to $60k. I’m serious.

It’s not just the government trying to deal with the “chicken problem.” One day I was at a roadside cafe with a friend and noticed a sign that said – “HELP US CATCH THESE CHICKENS. $5 PER HEN, $10 PER ROOSTER.” There were probably 20 hens, and 3 or 4 roosters, in the immediately visible area.

Moments later, a bum walks up to me and asks me, “Hey, man, could you spare some change so I can buy a sandwich?” You can guess how I responded….

“Funniest thing, man, see that sign over there? You can earn over $100 by rounding up these chickens. You’d eat sandwiches for a week off that.”

The man looked at me, dumbfounded and disgusted, and snarled “Well, why don’t you catch them and give them to me then, prick?”

Wow, seriously? The man sits down at a table and waits. A few minutes later, a young couple strolls up, and the man approaches them. Immediately upon being asked, the young man says, “Oh, sure man,” reaches into his pocket, and pulls out a five dollar bill. The bum walks up to the counter, orders his sandwich, and shoots me a nasty grin. The bum gets his sandwich, the cafe still has to deal with the chickens, and the man who gave him the money is now $5 poorer.

I had always been pretty generous up to that point, and would loan (or give) money to, or help out in whatever way I could, just about anyone who asked, regardless of the conditions. That experience changed me – and now, I have no guilt about turning down bums when they ask for money on the street (though it has taken me some time to abstract this logic to the rest of my life, as well). What I realized is that this guy didn’t contribute not because he wasn’t able, but because he felt he didn’t need to. Maybe it was a lack of pride – maybe it was a rationalization that “there will always be a hand out” – either way, there was a big difference between this bum’s beliefs and my own.

Good Charity, Bad Charity

I was raised in a middle class family that taught me the value of hard work. Ever since I was a kid, I’ve worked. Even while bouncing around the globe – I’ve worked hard. Sometimes I’ve needed help, and sometimes I’ve asked for it – but I’ve always tried to repay my debts – though not always as adeptly as I’d wished. Right now, I still have the ability to work and contribute to society, and thus asking for something without giving anything in return – be it government benefits or monies, money from strangers, food, or whatever – is immoral and unjust.

Giving money to the bum in Hawaii was an example of bad charity because the man, still young and strong – could have worked hard and rounded up the chickens around the restaurant – providing a service that would benefit the lives of others in exchange for the compensation he would receive, but instead chose to beg and sneer at those who suggested honest labor. Bad Charity is not just limited to giving money to bums who won’t work – Bad Charity happens at other levels too:

- When a company takes a government bailout after practicing unsound finance for years. Think of how the “financial crisis” was created – by banks making risky loans and then selling off the bad debts labeled as AAA debt. All of us have suffered because the public sector practiced bad charity.
- When a firm or entrepreneur accepts funds from investors or government to create a business they do not have the experience or intent to successfully implement. Solyndra would be a prime example.

I think that’s really where the line gets drawn. When a man has the capability to provide value in exchange for what he needs, yet chooses to take it by force, steal it, or beg for it, he commits one of the greatest sins. He who aids this man also commits a sin, and adds to the suffering of mankind.

Contrast this with some examples of good charity:
- Giving money or aid to poor children who cannot fend for themselves
- Helping an old lady across the street
- Helping the sick and injured
- Giving a job to someone who not only needs the job, but can perform it with excellence
- Preventing a rape, murder or burglary

Even giving money to bums on the street is *not* Bad Charity, given that those who you help are willing to do *something* to earn it:
- Giving to those who are willing to put their lives on the right path (for example, many charities, Christian and otherwise, help support those who are willing to trend upwards)
- The “chess men” who challenge you in a game of intellect
- Musicians and artists who play / create for your spare change

Good Charity reminds us that people can aspire to be better than they are – that men can be good. Bad Charity sets an example for the world and for those who receive it – that it’s OK to take fruits from the labors of others – that it’s OK to take through graft or force what others have sweated for.

The next time you’re tempted to take something you haven’t earned, or give to someone who has the capability to work for it yet chooses not to – remind yourself that your actions add to the net evil of the world.

Posted in Abstract, Philosophy | Leave a comment

What I’m Hoping to Get From Brooklyn Beta

I’m headed to Brooklyn Beta tomorrow in New York City. For those of you who haven’t heard of Brooklyn Beta, it’s advertised as the hippest conference for creators – the people responsible for building all the cool web toys that many of us take for granted. This year, it sold out within 4 minutes of ticket sales being opened. I was happy to get a ticket for the Wednesday Whatnot, even though I couldn’t score a pass for the entire week.

Take one look at the guest list and it becomes obvious why Brooklyn Beta is a place you might want to hang out at. Top VCs and the brains behind some of the best companies on the net are going to be here mingling, showing off their platforms and investments, and talking about what’s next. There are a few things that I’m particularly interested in:

- Talking to people about their technology stacks – namely the frameworks and libraries that are currently popular, and how scalability has been addressed. Essentially, I want to know how platforms with millions of users have evolved; how priorities have shifted over time, how painful/ painless scaling development teams was, etc.

- Talking to investors, startup founders and bootstrappers and getting a feel for how everyone stacks up against each other. Since funded startups have something like a 90% failure rate (for you stat geeks, I don’t have a citation for that), and there are some amazing bootstrapped companies out there (GitHub, 37 Signals, etc.), I want to get an “on the ground” feel for who took money, who didn’t, and how their paths and growing pains differed.

- Talking to people about their teams – how they were built, how often they’re changed, how rigorous the selection processes are.

Of course, you could ask any of these questions on StackExchange, HackerNews, or whatever – and probably get a ton of answers – but it’s not the same as meeting people, learning a bit about their background, and talking about what they see as the next step. You can learn more in a few focused days of interaction with the right crowd than you can in months of isolation – so that’s what I’m stoked for – meeting the great people who have built the modern web and hearing their stories.

Posted in Conferences, Goals | Leave a comment

Common PHP Compile Configuration Options

I’ve been compiling PHP from source lately. Some common baseline options I’m using:

sudo ./configure –with-mysql –with-apxs2=/usr/sbin/apxs –with-mcrypt=/usr/local/src/php-5.3.8/ext/mcrypt –with-config-file-path=/etc –with-openssl

In my local dev environment, I place all my language source files in /usr/local/src (ie php 5.3.8) and then symlink any needed command line features. For example /bin/php would symlink to /usr/local/src/sapi/cli. That way, If I recompile, I don’t have to change anything.

Posted in PHP, Programming | Leave a comment

Goals for the Coming Week

I recently posted my goals not only for the rest of the year, but for a long time in advance. A big part of reaching your goals is tracing the steps you need to take to get there. Goals for the rest of the year (mid-range goals) are supposed to support your goals for the next year, for the next 3 years, etc (more long range goals). – and goals for today, tomorrow, the coming weeks and months should support your mid-range goals.

I basically have three things I need to chip away at for the rest of the year:

- Getting database / inventory systems for Froedge Machine upgraded so I can leverage it next year in ecommerce applications.
- Launching Mango2 so I can build revenue for it next year and make it my primary source of income.
- Supporting a dozen gateways for Codeigniter Payments and finishing my port to FuelPHP, which is my contribution back to those communities.

Here’s what I’m going to do this week to support each of them:

- Add support to Codeigniter Payments for Chase Payments
- Implement Curl requests within FuelPHP and finish implementing the Authorize.net class
- Finish the user system, implement the payments and billing system for Mango2

I also have a physical fitness goal of running 40 miles per week. Over the past week, I did about 35, which puts my just short of my goal. I’ll need to average 6 miles per day, each day of the week, to get there.

In addition, I have to continue learning and reading to support my long term goals of mastery in several computer science subjects. Taking some classes online through Stanford, and as usual, taking wild tangents into something else (like last week an mcrypt installation ended with me learning how to compile PHP from source and learning how PHP extensions are implemented in C) should help with that. Next Sunday I’ll post about how I did on these weekly goals, and each morning I’ll think about what I must do each day.

Posted in Career, Goals, Health, Self Improvement | Leave a comment

How I fixed screen flicker on Acer S232HL widescreen – Macbook Pro

I hooked my new Acer S232HL widescreen monitor up to my Macbook pro using mini-dvi to HDMI and was getting some pretty crazy screen flicker.

I fixed this by changing the display settings from 1080i to 1080p. The display looks great now = ) Hope this helps someone!

Posted in Hardware | 2 Comments

FuelPHP Package for Working with Campaign Monitor API

Continuing my “Do it Yourself” exploratory programming trend, I took one look at the CampaignMonitor SDK today and decided I’d write my own. Their API is RESTful, well documented, and easy to work with, so why not?

Here is the final product: https://github.com/calvinfroedge/FuelPHP—CampaignMonitor-API-Package

What I like about this API wrapper is the simplicity, and specifying the HTTP verbs to be used for the request. For instance, if you want to do a GET request on lists, you do:

CampaignMonitor::lists('GET');

Or say you want to add a subscriber to a list. Just do…

CampaignMonitor::subscribers(‘POST’, ‘list_identifier’, $subscriber_details);

Pretty easy, right? I designed the class so that you can pass the params flexibly. The only requirements are:

1. Put your verb first
2. Include any method params in the same order they occur in the API documentation. IE http://api.createsend.com/api/v3/lists/{listid}/stats.{xml|json} should be formatted as:

CampaignMonitor::lists('GET', 'list_identifier', 'stats');

…since the identifier occurs before ‘stats’ in the API endpoint.

Other than that, you can pass an array of params to be included in curl post fields, and another optional array to add a query string onto the endpoint. Again, you can include these in any order. Here’s the snippet that helps out here:

foreach($params as $k=>$v)
{
if(is_array($v))
{
if(isset($v['qs_params']))
{
$added = 0;
foreach($v['qs_params'] as $p=>$pv)
{
if($added == 0)
{
$query_string = '?';
}
$query_string .= "$p".'='."$pv".'&';
++$added;
}

//Remove the trailing &
self::$_query_string = substr($query_string, 0, -1);
}
else
{
self::$_params = json_encode($v);
}
}

if(!is_array($v))
{
self::$_method .= '/'.$v;
}
}

The response handling almost certainly isn’t perfect (I only tested a couple methods), but it worked for the handful of methods I tested with. My disclaimer is that working with strings is messy business, so before you put this into production use make sure you test it ; )

Posted in FuelPHP, PHP, Programming | 3 Comments

Automatically Install WordPress Plugins when Your Theme is Installed

The thought of making a wordpress theme and requiring users to install plugins needed to make it work sounds pretty sucky. The thought of taking plugins and hardcoding them into my theme sounds even suckier. …And I hate things that suck. So here is how you can automatically install wordpress plugins when your theme loads:

Put this in functions.php or a file included by functions.php.


install_theme_plugins(array('my-plugin' => 'path-to-main-file.php'));

function install_theme_plugins($plugins)
{
foreach($plugins as $dir=>$file)
{
include ABSPATH.'/wp-admin/includes/plugin.php';
activate_plugin($dir.DS.$file);
}
}

Tomorrow I’ll add a script that checks the plugin server to see if the version is the latest (and if so) downloads a new one, and then activates it, when you install the theme. Cheers.

Oh, one thing to keep in mind. This: array(‘my-plugin’ => ‘path-to-main-file.php’) actually has to refer to a path that exists in your plugin directory. Just in case ; )

Posted in PHP, Wordpress | 2 Comments

Installing Apache Ant with Homebrew on Mac OS X

I just found out that you could use the Homebrew package manager to install remote packages as well as local packages. I needed Apache Ant while integrating HTML5Boilerplate with the FuelPHP Framework, and noticed it was not in the local packages. Here is the brew:

brew install https://raw.github.com/adamv/homebrew-alt/master/duplicates/ant.rb

Posted in Programming | 6 Comments