Category Archives: Book

Quantum Immortality – Organ Transplants

Organ Transplants

The human body evolved to reproduce, and then last just a while longer to help to raise the young after that. The fact that we live so long these days raises problems, because our bodies are not “designed” to do so!

There is no good evolutionary reason for a body to last very long after the reproductive age has been reached, yet we try our best to stave off death a while, by replacing the aging and dying parts of our bodies with younger, healthier parts.

A short history

The first successful transplant was in 1905, and was the cornea of an eye.

Nothing much happened after that for almost fifty years, and then after a stuttering start, medical research started producing wonder after wonder.

If you count the number of new transplant types that have been completed in each decade, the curve is unmistakable – we are fast on our way to being able to transplant virtually anything at all from one person to another. [1]

Donor shortfall

While organ transplantation is becoming easier over time, there is a problem with supply.

In order for you to receive a new kidney (for example), someone else must donate one of theirs. This involves finding someone with a similar body chemistry to yours, so the organ isn’t rejected, and also hoping that the person is willing to donate the kidney.

If no live donor is available, then you need to hope that someone dies to provide you with their kidney. This is a tragic thing to hope for.

A kidney is a best-case scenario, as humans have two each, so the donor can survive without it.

But if you need a heart, then the donor will most likely be dead before you get it. And you’d better hope that the donor didn’t die of heart disease!

The problem that there are simply not enough donors for each needed organ is a huge one. [2]

There is also a problem that organs can only survive so long outside the body, so once a donor has provided its organs, the organs must be transplanted nearly immediately, or they will die.

The current way to transport organs to the transplanting hospital is by freezing them so that decay is minimal. But even this can cause cell damage as ice crystals form and break apart the cells.

Luckily, these problems are also being solved.

Only this week, as I write, there is news of a liver-preserving machine which you can hook a liver up to. This device will then keep the liver alive, by emulating a living body. In essence, the liver does not know that it is no longer in a body, and continues functioning. [3]

Now that this has been done for livers, it can be expected that similar news will be announced in the next few years for almost every other organ.

Artificial Organs

The shortfall problem, that there are simply not enough donors per required organ, can be fixed with artificial organs.

Organs are generally very difficult to replace, as they do quite a number of different things. But some of the simpler organs have already been successfully replicated.

An obvious example is the heart. The first successful artificial hearts (not a pacemaker, but an actual pump) were created in the 1982. While their recipients lasted only 112 days and two years respectively after surgery, that’s still time that the patients didn’t have without the hearts.

This artificial heart design was primitive by present-day standards, but encouraged further research.

Artificial hearts are usually used as “bridges”, to keep a patient alive while waiting for a donor to supply a “real” heart. But sometimes, the artificial heart’s help gives the patients’ own heart enough rest to heal itself, and a transplant is no longer needed. [4]

Almost every organ can be replaced, given enough time and research.

Ears can be replaced with cochlear implants.

Eyes can be replaced, but artificial eye resolution is still very low. There are many different threads of research ongoing in this area. [5]

Some of the more “bag-like” organs can be very successfully replaced right now with artificial versions.

Bladders, trachea, arteries; these can all be created from stem-cells and/or plastics.

Legs and arms deserve a full chapter. There is some amazing work being done in these areas.

The most difficult organs (in the body itself) to replace are the pancreas, liver, lungs, and kidneys. These perform specialised functions, and currently, artificial versions are not small enough to implant.

I expect to hear within a year or two of the first completely artificial kidney implant. There already is an implantable artificial kidney available, but it’s a lot larger than a natural kidney.

In the future, I expect that the only organ that you will not be able to replace, will be the brain itself. Not because it can’t be moved, of course, but because the brain is your identity – there is no point replacing your brain with someone else’s.

However, having said that, if your entire body was failing, you could transplant your brain into a younger body.

There are a number of reasons you should not hope for this to happen, though.

For one example, in order for you to do a brain transplant, there must be a younger body available for you to transplant into. But if a younger body is available and it is healthy, then it makes greater ethical logic to offer its organs to save multiple people, instead of just you.

For you to get a whole new body all to yourself, you would need to provide it yourself, and i can’t think of any legal or even close to ethical way that you could do this!

If it turns out you need a whole new body, you’re probably better off looking into brain uploads instead, which will be discussed later in the book. Currently, brain uploading is not possible, but the technology should be ready soon; probably sooner than the first successful brain transplant.

Conclusion

In this chapter, you learned a short history of organ transplants.

There is currently a shortfall of available donor organs.

Artificial replacements are available for some organs, and others are on the way.

The only organ that will never be replaced fully is the brain, but we’ll talk more about that in a later chapter.

Quantum Immortality – Life Expectancy

Life Expectancy

Life expectancy is an estimate of how long a person is likely to live. It is difficult to give a single number as the answer, as it depends what country we’re talking about, how old the person is, whether the person is male or female, and other parameters.

But, let’s throw out some numbers anyway.

How long do people live?

The average life expectancy of a newborn baby is currently about 67 years. This means that each baby born today will on average live to about 67 years.

That number might not sound very large, but it’s more than twice as long as in any other era of humanity. Even just one hundred years ago, life expectancy was only 31 years! [1]

This number does not mean that a person that is born today is constrained by the number 67 and will definitely die at that age. Life expectancy is what we currently expect a person to die at. This changes over time as we develop new medicines, better understanding of how the human body works, and better surgeries to replacing aging or faulty organs. We are not constrained by the limits of medicine at the moment of our birth. We can expect to take advantage of new medicines as they develop through our lifetimes. [2]

There is a very important distinction to be made here.

The above numbers are average numbers, in that they take into account all people of that time, including those that take care of themselves, those that don’t take care of themselves, those that live in wealthy countries, those that live in poor countries.

It makes sense to say that a person who lives in a more wealthy country and takes care of themselves, will live longer than a person who lives in a poor country and doesn’t take care of themselves.

Because life expectancy increases over time as our researches figure out more and more, the longer we live, the more likely we are to live even longer.

For example, let’s consider diseases such as HIV/AIDS and cancer. in the 20th century, being diagnosed with either of those was virtually a death sentence. But today, there is a “functional cure” for AIDS, and there are a number of potential cures for cancer also being worked on. All you need to do is survive long enough for the research to find better solutions, and those diseases will no longer be a concern for you.

Preventing the common causes of death

Currently, the top five killers of humans are: [3]

  1. heart diseases (cardiovascular)
  2. infectious/parasitic diseases
  3. heart diseases (ischemic)
  4. cancer
  5. stroke

So, logically, if you try to avoid those problems, then you should be much less likely to die in any particular year.

This means exercise, avoiding or cutting down on toxic habits such as alcohol and smoking, and avoiding stress. [4]

If you are serious about living forever, then you should read about each of the above causes of death, and try to change your habits so you are less likely to die of them.

If we add Quantum Immortality into the conversation here, then you could say that you don’t need to make any change at all to your habits, as you will survive everything that is thrown at you, through sheer statistics.

But, there is a very big difference between “surviving” and “living”.

Heart attacks hurt. A friend of mine, who had his first heart attack at age 32, described the pain as “like a truck sitting on my chest”. He survived that heart attack and at least one more, and is currently 52 years old and very healthy, but I’m certain he would have preferred not to have had the heart attack in the first place!

I have lost a few friends to cancer. In some cases, the cancer came and took the person within a year or two of diagnosis. In one very lucky case, the cancer (leukemia) took nearly twenty years to take the person even though the doctors said she had only a few months to live.

Cancer is not currently curable, but it is certainly preventable. [5] There are a number of potential cures being worked on at the moment, so Quantum Immortality says that you will survive cancer long enough to get cured. Or at least long enough to go onto a course that maintains your current state and then eventually you can be cured. But, considering that cancer is preventable in most cases, it is better that you don’t get it in the first place.

A look at Influenza

It’s worth looking back in time at how the list I wrote above has changed.

In the early 20th century, the number one killer was infectious diseases such as influenza. Infectious diseases is currently the number two killer, but Influenza is much less fatal now than it was then.

Influenza still kills tens of thousands of people every year, but as we learn more about it, it becomes less and less dangerous.

The worst deaths occur during “pandemics”, when fatal forms of influenza evolve and kill a huge number of people before we figure out how to solve the problem.

There were three quantified pandemics during the 20th century. Each of them killed less people than the pandemic before it on the list:

Killed Year Name
50,000,000 1918-1920 Spanish Flu
1,500,000 1957-1958 Asian Flu
1,000,000 1968-1969 Hong Kong Flu

One of the major reasons for the decrease in numbers is vaccination.[6]

Vaccination involves injecting a dead version of the virus into your body so your immune system can figure out how to defend itself against it. Then when the real thing comes along, you might get sick for a while, but you are much less likely to die.

There has so far been one pandemic in the 21st century, called the Swine Flu pandemic.

Only about 16,000 people died this time. [7]

I think the most important thing to take from this is to realise that the effort that we (as a race) put into solving the most common causes of death, is paid off with an increase in longevity in the general human population.

We live much healthier lives these days than people in the early 20th century, and it’s not like we actively put any effort into it – it’s almost like we “absorb” healthy lifestyles by osmosis. Our friends exercise so we exercise as well. Our friends drink less or smoke less so we do the same.

Our environment is improving, and we are improving along with it.

Conclusion

In this chapter, we learned that humans are on average living twice as long now as they have ever lived before.

We also looked at the top five causes of death, and how prevention of these causes is actually not all that difficult.

We also looked back in time at how one of the historical number one causes of death is not such a huge deal these days because of medical advances.

Quantum Immortality

Quantum Immortality


At the time of writing, the oldest person ever to have lived was Jeanne Calment, who died at age 122 years, 164 days in 1997.

It is my belief that you, the person reading this book, will far outlive Jeanne. In fact, you will simply not die, ever.

And you won’t have to take up a special diet, or join a religious order – it’s just a consequence of how reality works.

This is an outrageous claim, so I need to explain how it works.

How does Quantum Immortality work?


Quantum Mechanics (QM) is one of the most accurately tested theories of how the universe works. QM is hard to understand, but its predictions have been tested and retested for a century, and have held up. [1] [2]

QM says that every time anything happens, every single possible version of the event happens, and one is “chosen” to become real (to “cohere”). This is described as “collapsing the wave”, or “quantum coherence”.

There is a very interesting interpretation of QM that leaves out the collapse, and simply says that all versions of the event happen, and each can be said to be separate versions of reality; each of which is as real as the one you are in right this moment. This is known as the “many-worlds interpretation”. [3]

A consequence of the many-worlds interpretation is something called “quantum immortality” [4]. It’s also known as quantum suicide, but that’s a rather negative name for something so extraordinary and life-changing.

The idea is basically this:

  1. Let’s say you are lying in a hospital bed dying, and the doctors say you have a 50/50 chance of living to see another day.
  2. The next day arrives.
  3. Because there was a 50/50 chance of living or dying, the many-worlds interpretation says that you are dead in half of the newly branched universes, and alive in the other half.
  4. You cannot experience being dead, so you wake up that morning and dare the doctors to come up with another prediction.


This works, whether the prediction was 50/50, ¼, 1 in a million, whatever! If there is even the slightest chance that you will survive, then you will survive.

Do other people die?


You have probably attended funerals, or lost friends to accidents, disease, old age.

Your question at this time is: if quantum immortality is true, then why are those people dead?

Well, let’s consider the case of cousin Bob, who died after his car brakes failed and he slammed into a car. You are at his funeral, wondering why Quantum Immortality doesn’t mean that he’s alive.

There are many ways that this could have played out – the car brakes don’t fail, the brakes fail and the car misses the tree and slides to a halt in a muddy field, the brakes fail and the car hits the tree and Bob is thrown clear through the window and survives with a broken leg, or the brakes fail and there is a funeral held a few days later, where you wonder what happened to Quantum Immortality.

The fact that you are attending a funeral means that you are conscious of a reality where Bob did not survive. Bob is not conscious of this reality, so for Bob, this reality is not real. But for you, it certainly is.

Bob could have survived the accident in many ways, and because Quantum Immortality says that Bob can only be aware of versions of reality where he can be aware, this funeral simply did not happen. The Many-Worlds interpretation says that every possibility is its own reality, so Bob actually survived his accident and this is all a non-issue for him.

Unfortunately for you, you will never speak to Bob again – he’s dead in your reality. But, you can take heart in knowing that he’s alive and well in his own reality.

This, by the way, has huge “spiritual” implications. It means that everyone lives forever, even if you see them die. All you saw was one possible version of that person dying, but you need to keep in mind that every possible version of that person exists, and at this moment, the versions which could possibly be alive somewhere are alive.

This means that there is no true death. You may see people die, but they actually experience something different. You might see someone breathe their last on a deathbed, but in their own experience, they took that one last breath, and followed it with another and yet another, until they finally got over their ailment and got out of bed.

But what about when the odds are against you?


Naysayers may say that in some cases, it’s just too unlikely that survival could happen.

Let’s say, for example, that you fall from a tall building, and there is a one in a million chance that you land on a car roof (like in so many films), and a further one in a million chance that you survive this and get off the car roof and go about your business.

Well, that’s a one in a trillion chance that you survive the fall. That couldn’t possibly happen, right?

QM says that every single possible event has a probability, and the many worlds interpretation says that they all have their own realities.

So, in most realities, you might slam into the ground and you are dead, full-stop.

Then there are the realities where you fall a little to the left or right of that spot, closer to the parked cars, but still die. And then there are further realities where a car is driving along the road below and you just miss it and slam into the road behind it.

Each of those realities are real. But you are not aware of them.

You are only aware of the realities where either a gust of wind blew you enough that you landed on a parked car, or you landed on the moving car below.

Even then, there’s a million to one chance that impact with the car roof kills you.

Well, guess what? Million to one chances are a dime a dozen to QM. In Quantum Mechanics there are practically an infinity of possible results, so there are an infinite number of worlds in which you are a survivor.

Sounds great, right? Want to go jump off a building now to test it? Don’t.

You see, even though Quantum Immortality says that you will survive, it does not say that you’ll be all in one piece…

You will survive the fall, but you will very likely break most of your important bones, and be in hospital for months or years before you can hobble out. It’s survival, but it’s not nice.

Conclusion


So, let’s summarise then with this:

You will live forever.

You will see people die over the years, but should be happy that they are living forever in their own realities.

Even though you are essentially immortal, you can still be hurt badly, so don’t do stupidly dangerous things.

review: Expert PHP5 Tools

In short: great overview of the various tools and processes that can be followed to make working in PHP easy and manageable. I have a new employee here in the office who will be getting this book after me, to quickly bring her up to speed on good practices.

The Good

As you might guess from the “new employee” comment, even though the word “Expert” is in the title, you don’t need to be an expert PHP programmer to use this book. It’s an all-round overview of the programs you might use during your day-to-day programming life for the next few years.

As the author (Dirk Merkel) suggested in the book, some people may disagree with some choices in the book. For example, I am a fervent Vim user, but the book chooses Eclipse as its programming environment of choice.

From a broader point of view, the Eclipse IDE may be the correct one for programmers to use, as it offers much more than just a text editor. As for me, it’s hard to change an old dog’s habits!

The book includes some handy reference notes for various tools, such as SVN or phpDocumentor. It’s good for people that are not used to reading online references for everything to have them all in one book.

Each chapter is immensely in-depth. To the point that it’s almost like each chapter is a mini-book on its own subject. In some cases the chapters include everything you might ever use on those subjects.

For myself, I’m interested to try some of the suggestions in the Continuous Integration chapter and throughout the book, as I already run a few projects where updates are more important than releases. I’m especially interested in integrating SVN with automated testing and style-checking. Test-driven Development is described in the book, and it certainly seems more robust than my current “deadline-driven development” style!

The Bad

There were code samples in there that could have been shortened immensely by choosing a different spacing scheme or reducing the comments. For example, in the Debugging chapter, there is a code sample that goes on for 9 pages. That’s a lot of code to read… If the empty lines and comments had been removed or reduced, Dirk could have cut it down to maybe 4 or 3 pages, making it much more readable in print. As it was, I did my best to read through it, flipping back and forth between pages to find where references went or came from.

The Ugly

Actually, there wasn’t really anything in this book that I’d call ugly, apart from the overly long code examples.

Conclusion

Immensely useful for the professional programmer. Especially a programmer who needs to fit into a team.

I’m no beginner myself, and picked up quite a few tips throughout the book.

Buy this book – it’s worth it.

update: CMS design with jQuery and PHP

EDIT: The CMS that the book is about is available to download here.

I got an “urgent” email recently from my Packt coordinator – she told me that if I kept writing my book at the rate I was writing, then it would end up being about 500 pages.

Thing is, though – it would be tricky to reduce the chapters I’ve already done, as a half explanation is as good as no explanation at all.

So, I looked over the planned chapters again, and saw that the final three could probably be dropped without affecting the core content of the book – they were just more example plugins showing how to integrate various things with the CMS.

The book itself is on how to build a CMS in PHP, that uses jQuery to make administration easier. That has been accomplished already in the existing chapters (1-7).

I suggested to Packt that I would drop the final three chapters and rework the earlier chapters so the book was more easily read (a 40-page chapter is /not/ easy to read).

Got an email back from them yesterday saying that the plan sounded good.

So the current plan is:

  • Finish chapter 8, which is on panels and widgets.
  • Write chapter 9, which will build a plugin demonstrating panels and widgets.
  • Try to break the earlier chapters apart so that there are more chapters, with less pages per chapter.
  • profit

I think I’ll be finished the current chapters within three weeks, then take a week or two to rework the earlier chapters, then another month for rewrites, and finally the book will be published 2/3 weeks later.

So, the book may be out within two months.

After this, I’m taking a break from modern technology to write about baroque technology – I’ll be writing a book on how to build a cheap clavichord.

what I'm up to

As usual, I’m behind on stuff.

I just submitted chapter 3 of my upcoming book “CMS Design with PHP and jQuery”, and chapter 4 was due to be complete and sent two days ago.

My clavichord project stalled when the cumulative number of mistakes made it incredibly unlikely I’ll complete it in a usable fashion.

In work, I’m behind on a pretty large online-store project, but in that case I’m okay with it – I wasn’t slacking; things are just very busy at the moment.

My piano playing has also stalled – I’ve been trying to learn The Heart Asks Its Pleasure First for the last month. I’m stuck on the final page, where the left hand is all over the place and the right has an intricate tune to play. Its all in my head, but I just can’t play it smoothly. Thinking of putting that on the back-burner and going onto Bach’s 2-part inventions instead.

upcoming

Packt have asked me to review Expert PHP5 Tools. Looking forward to it. It’s got some stuff in it which I’ve read about but never tried. Including: UML design of applications, incorporating tests into subversion submissions, and automated documentation of source (among other things).

My piano teacher found an examiner who will be testing in Monaghan next month, so I’ll finally be able to get grade 2 out of the way. I’ve been practicing grade 2 and 3 tunes for months. Playing 6 tunes every day before I do anything else has been reducing th amount of time I have for the rest of my practice, so I’ll be glad to get this one passed as well.

I’m trying to push myself to get the current book finished as soon as possible. This is difficult as writing a CMS is a much more complex job than writing a cookbook of techniques. The chapter I just finished had 40 pages in it. By the 40th page of the previous book I was already into chapter 3. Chapter 2 wasn’t much smaller either!

When this book is finished, I’ll be starting a new one, on building a clavichord as cheaply as possible. Because I failed with the current one, but learned quite a lot from it, I feel I’ll get it right this time, and would like to document it as I go. There’s a lot of math involved in building a clavichord, and I think I may even get a good programming application out of it!

After that, I’m thinking of starting up contact juggling again, and completing the book, this time with videos.

When I get the time, I’d also like to get back into building robots. I think the gardening robot is a bit beyond me at the moment (involves some very complex AI), but I thought I’d try build a digger bot. You tell it what you want dug, where to put the debris, etc., and it gets to work.

CMS Design with jQuery and PHP: moving a recaptcha form

reCAPTCHA is a free captcha service which lets you use their captchas for your programs.

I wanted to create a login/password-reminder page, with recaptcha used in both forms.

Unfortunately, you can’t have two recaptcha images on the same page, as every time the image is displayed, it is a new image and the old one is no longer valid (which means that if it’s used in two forms, you can only ever submit the second one.)

A solution that came to me is to “move” the captcha from one form to the other, so you’re only ever actually using one recaptcha.

So how is it done?

demo

In the demo, I’m using jQuery UI to separate the forms into two tabs.

If you look at the source, you will see there is one recaptcha object, in the first table. The table row has the ID “captcha”.

The entire JavaScript used in the demo is this:

$(function(){
	// remove the captcha's script element
	$('#captcha script').remove();
	// set up tabs
	$('.tabs').tabs({
		show:function(event,ui){
			// if the captcha is already here, return
			if($('#captcha',ui.panel).length)return;
			// move the captcha into this panel
			$('table tr:last',ui.panel).before($('#captcha'));
		}
	});
});

The first thing that’s done is that the captcha’s <script> element is removed. If you don’t remove it, then when the table row is moved, the script will be re-interpreted, causing breakage.

Now, the tabs are initialised. We set the show event to run a little function. That function checks to see if the captcha row is contained in the newly-shown panel. If it’s not, then it’s moved there using this line:

$('table tr:last',ui.panel).before($('#captcha'));

The above line means “insert/move the #captcha element in front of the last tr in the table contained in ui.panel“.

This is part of the User Management And Access Control chapter of the up-coming book “CMS Design using jQuery and PHP” ( a sequel, sort-of, to my jQuery 1.3 with PHP).

ToDo

List of things off the top of my head that I want to do:

  • write a book. already had a non-fiction book published, but I’d love to have an interesting an compelling original fiction idea to write about. I’m working on a second non-fiction book at the moment.
  • master a martial art. I have a green belt in Bujinkan Taijutsu (ninja stuff, to the layman), but that’s from ten years ago – found a Genbukan teacher only a few days ago so I’ll be starting that up soon (again, ninja stuff).
  • learn maths. A lot of the stuff I do involves guessing numbers or measuring. it’d be nice to be able to come up with formulas to generate optimal solutions.
  • learn electronics. what /is/ electricity? what’s the difference between voltage and amperage? who knows… I’d like to.
  • create a robot gardener. not just a remote-control lawn-mower. one that knows what to cut, what to destroy, that can prune bushes, till the earth, basically everything that a real gardener does.
  • rejuvenate, or download to a computer, whichever is possible first. science fiction, eh? you wait and see…
  • create an instrument. I’m just finishing off a clavichord at the moment. when that’s done, I think I’ll build another one, based on all the things I learned from the first. followed by a spinet, a harpsichord, a dulcimer, and who knows what else.
  • learn to play an instrument. I’m going for grades 2 and 3 in September for piano. I can play guitar pretty well, but would love to find a classical teacher.
  • write a computer game. I have an idea, based on Dungeon Keeper, for a massively multiplayer game. maybe I’ll do it through facebook…
  • write programs to:
    • take a photo of a sudoku puzzle and solve it. already wrote the solver.
    • take a photo of some sheet music and play it.
    • show some sheet music on screen, compare to what you’re playing on a MIDI keyboard, and mark your effort.
    • input all the songs you can play on guitar/keyboard. based on the lists of thousands of people, rate all these songs by difficulty, to let you know what you should be able to learn next.
    • input a job and your location. have other people near you auction themselves to do the job for you. or vice versa: input your location, and find all jobs within walking distance to you where you can do an odd job for some extra cash (nearly there: http://oddjobs4locals.com).
    • takes a photo and recognises objects in it (partly done)
    • based on above, but can also be corrected and will learn from the corrections (also partly done)
  • stop being damned depressed all the time.

There’s probably a load of other stuff, but that’s all I’ve got at the moment!

CMS Design using jQuery and PHP: the core

I submitted chapter 1 of “cms design using jquery and php” yesterday.

I’ve been building and using CMSes for over ten years, and the more I do it, the more I realise that “less is more”.

In the beginning, I was writing CMSes that had absolutely every aspect of the requirements hard-coded. That made the system fast but inflexible.

Over the years, though, I started figuring ways of breaking the system up into more modular bits and pieces, that could be enabled/disabled depending on the job.

This is the essence of what “plugins” are about – you have a single core system which includes only the absolute essentials, and into that, you put whatever plugins you find necessary for the job you’re doing.

The trick, though, is in deciding what is a plugin and what is not. This is very important to figure out – if something should be a plugin, it should not be in the core, thus making he core more stable and manageable. Conversely, if you make something into a plugin which is necessary for normal use of the CMS, then it makes the system less stable.

An example of this dilemma is user logins. Obviously, you need to have user logins for the admin area to work, but you don’t need user logins on the front end of the site.

So, should user-logins be a plugin or core functionality? The solution is a mix of both – you need to create a hard-coded user login specifically for the admin area, and if you want users logging in to the front end, that is a plugin, even though they both use the same database. The difference is that the admin login area is at a defined point (when you access the admin area), while making the frontend login into a plugin allows you to place a login anywhere you want.

Anyway – over the years, I’ve whittled away at my own CMSes until I realised that the core functionality of a CMS consists of just three things:

  1. display and editing of “normal” pages
  2. user and role administration
  3. plugin management

It’s impossible to cover those three items in just one chapter, but once they are covered, that basically completes the CMS!

When you have the above three items completed in your CMS, you can then work completely on plugins, making the system stable and yet flexible.

Of course, there are some fine details (templates, UI, optimisation, DB structure, etc.) that go into completing those three items, but that’s basically it.

CMS Design with jQuery and PHP: postage and packaging prices

This article is based on work which will be expanded more fully in the book, when I get to that chapter.

Every time we do an online store here in webworks, the postage/packaging is different. In one case, for example, postage is free over €50 euro, in another, it depends on where it’s going, and in the latest, it depends on a load of factors including where it’s going, what the weight of the products is, and what delivery option was chosen.

Up until now, hand-coded the postage rules. Everything else was handled by user-friendly parts of our CMS, but postage was such a random thing that we couldn’t find anything common enough that we could make a generic P&P handler.

The finished product is more complex than this example, but I’ll describe a cut-down version of what we’ve done, with countries and parcel-types removed.

admin demo – demo of UI for generating P&P rules

The first demo shows how the postage-and-packaging rule-set is created, using an “if-else” flow generator to build up the logic of the thing, and after each major action, convert the current state into a JSON string which can be saved.

The PHP is not really important in this one. The JavaScript handles everything. It translates a “seed” JSON string into a graphical representation of the rules, which can then be manipulated and finally translated back (automatically) into a JSON string to be saved in a DB (or session in this case). source for the PHP, source for the JS.

The frontend does its work in the background:

frontend demo – using those rules to evaluate P&P (visit admin first).

In this case, we enter values – total, weight – and run through the rule-set to find out what the P&P ends up as.

The source is suprisingly small, using a small recursive function to dig through the rules, no matter how deep and complex they go.

Here’s the recursive function (see source for rest of file):

function os_getPostageAndPackagingSubtotal($cstrs,$total,$weight){
  foreach($cstrs as $cstr){
    if($cstr->type=='total_weight_less_than_or_equal_to' && $weight<=$cstr->value)return os_getPostageAndPackagingSubtotal($cstr->constraints,$total,$weight);
    if($cstr->type=='total_weight_more_than_or_equal_to' && $weight>=$cstr->value)return os_getPostageAndPackagingSubtotal($cstr->constraints,$total,$weight);
    if($cstr->type=='total_less_than_or_equal_to' && $total<=$cstr->value)return os_getPostageAndPackagingSubtotal($cstr->constraints,$total,$weight);
    if($cstr->type=='total_more_than_or_equal_to' && $total>=$cstr->value)return os_getPostageAndPackagingSubtotal($cstr->constraints,$total,$weight);
  }
  $val=str_replace('weight',$weight,$cstr->value);
  $val=str_replace('total',$total,$val);
  $val=preg_replace('#[^0-9*/\-+.\(\)]#','',$val);
  if(preg_match('/[^0-9.]/',$val))eval('$val=('.$val.');');
  return (float)$val;
}

The switch block goes through the various “if” types that can exist in the flow model, handling each of them recursively and return their values to the caller.

If no “if”s are encountered, then the ruleset has found an answer, and we return that answer.

Before returning it, though, we parse the value of the answer. This is in case the answer is a math formula to do with the weight or total of the item.

For example, An Post have definite prices for packets to Europe up to 2kg (which is 10.75), and beyond that, it’s 3 euro extra for every extra kg.

That translates to a load of definite “if” statements, and an end value of “(weight-2)*3+10.75″ for the final “else”.

So, we convert recognisable words such as “weight” or “total” to numbers, make sure that we’re only left with parseable characters (and not something that can be used to hack), and eval it to produce the result.

Obviously, the full product is more complete than this, with safeguards against faulty formulas, extras to handle countries and envelope types (parcel/packet/envelope), but this example should give you a few ideas if you’re building your own P&P handler.