PHP Nested Ternary Operator Order

Now let’s say we have the following pseudo-code that we want to implement in several programming language:

bool condition = true;
string text = condition == true ? "A" : condition == false ? "B" : "C";
print text;

Here is the implementation in Javascript:

let st = true;
let text = st === true ? "A": st === false ? "B" : "C";

Here is the implementation in PHP:

$st = true; 
$text = $st === true ? "A": $st === false ? "B" : "C"; 
echo $text;

As a bonus, I also try the same pseudocode in C#:

bool st = true;
string text = (st == true) ? "A" : (st == false) ? "B" : "C";

Now let’s guess what is the result of variable text? The expected value should be A, which is already correct in other languages, but PHP​ produces B. Well, this is not a great discovery but many PHP developers may be missing this after all, so I think it’s worth archiving. Parentheses may fix them but it’s making things ugly, looks like it’s better to stick with if-else statement then.


Why PHP is bad and why it isn’t

Nowadays programmers consider PHP as a very bad programming language. One of the example is in this comic strip, saving the princess with programming language. But why is PHP considered bad and why does it is very popular out there?

The good

In general, PHP is a good language to start learning programming with.

It’s easy to setup and start

PHP is very easy to setup, especially for beginner. Just use XAMPP (for windows) and LAMP (for linux), and drop the code in htdocs and everything will go well. Just search in google for “hello world php xampp” or “hello world php lamp” and you’re good to go.

Furthermore it’s one of the easiest language to setup shared hosting, making it very easy to make your own website.

It’s very forgivable

PHP is dynamic typing, meaning you don’t need to specify whether an variable is string, int, specific class, etc. And it’s string concatenation is different with numeric additional, making it less ambiguous than javascript’s dynamic and don’t need type conversion. It’s very easy for beginner to start with.

And PHP variables works very well with HTML. Almost all native variables can be printed to screen by using echo, while array and object need special treatment.

Furthermore, using undefined variable only resulting in notice, and can be easily suppressed. But beware, both are considered “bad habit” in programming, so take it as learning features. There are also more exceptions that usually result in error in other language, that can easily suppressed in PHP.

It’s both procedural and OOP

PHP can serve procedural code, and OOP one. It’s very common to start learning programming with procedural, and learning OOP next, and it’s easier in same language.

Furthermore, PHP is a C-like syntax programming language, and there are many good languages in C-like syntax, like Java, C# and javascript. It’s C-like syntax is better than python (which is also a good starting language) “if” you aim to move later to those language.

Frameworks and tutorials are abundant

With many framework and tutorials out there, someone can search any problem or topics that they currently worked at, and finding many pages of google results. It’s very easy to find answers to PHP problems nowadays.

Furthermore, many PHP framework are using MVC (Model View Controller) pattern, which is one of the most common pattern in web programming. Learning them can help transition to other good languages using MVC pattern, such as Java MVC spring, C# Asp.Net MVC, NodeJs MVC frameworks and many more.

Furthermore nowadays PHP has composer, which is good to handle library as packages, which is almost all new languages use. And PHP has many CMS which make creating webpage like wordpress CMS easy.

The bad

So why is PHP considered bad? Well you need to at least good in programming to know it’s limitation and bad side.

It is not strong, static typed

PHP starts as dynamic, weakly typing language, helping to customize HTML pages ages ago. Up to this day, it still support dynamic typing, while supporting some type hinting at arguments and property level. While dynamic typing is good to start learning programming, it’s not good at complex business process.

However, being interpret language means the type hinting can only trigger when executed. So we won’t get any type error up until the portion of code is executed, as opposed to Java/C# where it can be caught compile time.

Moreover, PHP7, even after getting scalar type hinting for string and int, still not having generics for array. Without any means to type checking array, it’s harder to do type checking and enforce reliability, especially in business process (accounting).

It doesn’t have multithreading options by native

Without using additional components “PThreads”, PHP doesn’t have any options to emulate multithreading. It isn’t that PHP cannot do multithreading, however the problem lies in how “PThreads” works. It copy the current “process” state (loaded classes, etc) into another process and execute them concurrently.

In my experience with PThreads for PHP 5.6, (maybe I just lack configuration, correct me if so) PThreads use bigger memory than other programming languages, notably C#, Java and NodeJs. Moreover it’s harder to catch exception and to debug process spawned by threads.

So it doesn’t support multi-core process

In case of heavy background process or batch processing, most of the time multi-core support is a requirement.

It doesn’t have memory-persistence cache

PHP is run-and-forget scripting language, which load all it’s needed reference class on beginning of request (and during execution for lazy loading one), and to flush them later. The process takes time, and while PHP7 doing JIT to cache some of it’s code, it’s still not efficient because they need to be loaded for every request.

In contrast with PHP’s scripting, NodeJs and C# Asp.Net MVC (haven’t use java, but should be similar) run a server, and keeping the loaded classes (scripts) in memory, making them more efficient.

It’s dynamic typing takes too much memory

Looks like it’s mitigated in PHP 7, however in PHP 5.6 below, the dynamic variable in PHP takes too much memory. It’ll soon be a hassle when working with big variables, big file or many records of data.

And even if PHP7 is more efficient, it still can’t beat C/C++ level of memory usage per variable. And arguably, so do as in comparison with static typed language, such as Java and C# and the currently rising golang.

It’s data access doesn’t support multiple-result sets

Apply for MySql at least (looks like it supported in PostgreSQL). PHP cannot return multiple tables in one query. Let’s say that you have one procedure that returns 3 select queries, PHP MySql driver can only return one.

Many of it’s library support is configured at installation level

Some of the native library for PHP is configured during installation (gcc make and phpize). Some of the examples are zip (–enable-zip), thread safety (–enable-zts) for pthreads. It makes binding configuration to app repository level harder and reduce portability.

In conclusion

PHP is a good language to start programming with, easy to setup and have many libraries / framework / CMS. However in case of advanced use by expert programmers, PHP doesn’t really meet up the requirement.

Choosing the right tool for the job

This morning I read the following article: The myth of the “right tool for the job”. The short summary for that article is: do not choose programming language based on the task / project, but choose based on popularity, documentation and ease of learning. While that statement is not completely wrong, it’s also not perfectly right.

I dare you to use PHP for highly reliable, complex business process

Dynamic type makes developing reliable business process hard, because many times you don’t know which kind of variable being processed. This seems possible with HHVM and PHP7 due to type hinting, however the lacking of generic, runtime validation, and ability to re-assigning different type to same variable is making it harder. Consider the following code:

$var1 = new \ComplexObject(); 
$var1 = "Hello World";

I agree that it is a very bad code snippet. However it is possible in PHP and do not produce any error. Meanwhile in static typed language like C# or Java you will get compile error. Yes, compile error which validate variable types in compile times and produce error if the type is somehow not valid (except type casting).

Why compile-time type validation would that matter compared to runtime validation in PHP? The runtime validation in PHP won’t produce error if the code / function / module isn’t being triggered during process. That means to validate the type hinting at specific function, you’ll need to run all process that use the part of code to check whether the type is valid or not. Meanwhile compile time validation will produce error even if the part of code is not used anywhere.

So in short, if you need highly reliable, validated business process, then static typed, compiled language like Java or C#is better than dynamic typing like Nodejs or PHP.

Developing template-based process in Java or C#?

C# or Java is static typed language, so any template-based or string pattern process will be hard to develop. For example, the following code is a part of swagger JSON specification:

        "type": {
            "type": "object",
                    "type": "number",
                    "example": 1
                    "type": "string",
                    "example": "Information"
        "description": {
            "type": "string",
            "description": "Description",
            "example": "This is the description of Programming Language"

The code is swagger code for part for fields of object. If you tried to parse and process the JSON object in Java or C#, you’ll get a headache due to static typed. Meanwhile you’ll get native support when parsing that code in nodejs, or in PHP you can easily decode the json string to PHP objects.

Real time messaging service

I haven’t use Erlang so I don’t know how superior it is in term of messaging (chat) service. Whatsapp using Erlangfor their messaging service, so it’s somehow good at the job. For this case I’ll promote nodejs over Java, PHPor C#.

Nodejs is non-blocking single process server, meanwhile Java or C# is blocking single process server. PHP is the worst here, it spawn another thread or process for each request. So everytime a data is sent to PHP service, it’ll spawn another thread, loading all classes then begin processing the data. It take too much flow over single simple process.

Java or C# is good, however the non-blocking Nodejs is the superior one here. Nodejs will able to handle more requests in lower performance cost.


Some languages are good for some task, while the other are good for other kind of task. Finding the best language for specific task it not optimal. However deciding not to use programming language which is bad at the task is many times better than sticking to existing, used language in your environment.

I’ve just realized that my web app is not keyboard friendly. How’s yours?

Visual FoxPro!

Today I’ve met a senior programmer. He used visual foxpro for his latest ERP system. Honestly I’m amazed with what kind of features that foxpro can provide and how good they are. Foxpro, really? That old not-popular programming language? Maybe that’s what you have in mind. But honestly, you’ll be amazed by how good Foxpro interact with database objects. Moreover, how fast the database is! Though it haven’t being tested over 50 users though.

I’m amazed at the features of foxpro!

So? Do we all move to foxpro all together? No, foxpro is good, but not in every aspect. One of the reason is that application structure is very tightly coupled with the data object, which is good for administrative tools but not for the other. I’m not using foxpro, so I can’t give more reason, and that topic is not what I want to discuss now.

It’s a desktop app!

I just want to shared that the visual foxpro that has been developed is desktop app. I must admit that no matter how good you are at web programming, you can’t defeat the UI functionality and keyboard-friendly functionality of desktop apps. There isn’t even safe cross browser hotkey that can be used in web. While in app, you can easily navigate using arrows, tabs, function keys (I’m pointing at you, F1-F12!), page up page down, control + keys, etc. Not to mention the responsiveness, and the functionality of one-page application (nah, ajax can’t even compete with it).

Web apps won’t win against desktop in UI and keyboard functionality

Man, I missed the desktop-based development time of my university time.

But that’s it. Desktop integrated system is losing popularity over year, as better web environment is emerging such as web socket, html5, css3, etc. But I must say that web apps will never beat desktop apps for transaction-intensive activities. No POS (point of sales) in hypermarkets using it.

Hypermarket using web-based POS? How slow will it be?

Do you imagine integrating barcode scanner with web apps? Do you imagine using mouse to choose which payment method? What will happen if they need to wait for respond after submitting, waiting for the payment change? That won’t do. We must back to our very first factor of application development: requirement. If they require it, then it must be done.

The very first factor of application development: requirement

So, we back to desktop app?

Yes for that particular activities. But how many of those transaction-intensive activities are there? There won’t be many of that kind transaction in today’s business. More often we need flexibility and portability more than keyboard shortcut. Let’s say reports, approvals, notes, attachments, all of them are better cross-browsers and portable. Employee self service (reimbursement, leave) is better online. Marketing will be more awesome online, since it can directly communicate to media via links and connections.

Of course we must ignore web-specialized features such as online trading, blog and social media though.

reports, approvals, notes, attachments, reimbursement, leave is better online


We go back to the very first rule of application development: requirement. If it is required to have intensive-transaction application or embedded devices (printer, barcode scanner), then use desktop. If not, then it’s better web since it’s easier to access and easier to maintain and publish. So, compare and plan before deciding the approach!

Embed Asp.Net MVC views in class library dll

If you’re anything like me, you may want to define asp.net mvc views in class library, so that it can be used from anywhere. However, it’s not an easy task, regarding the MVC architecture of asp.net mvc. The view normally be placed at Views folder physically, making us unaware of possibility to embed the view and controller to shared library (dll).

Define view in library

Create the view file

You can create the view file inside library project. If you cannot find the view template from add file, you can choose text file then rename the extension as cshtml (razor) or aspx.

Set the view as embedded resource

The view file need to be set as embedded resource during compilation, so that the file can be referenced from other projects.

Set the build action into embedded resource

Set the build action into embedded resource

How to make asp.net mvc find embedded view

There is a way to tell asp.net mvc to look up from specific source. One of them is embedded view. It can also get from database but I haven’t tried that or need a case for that.

To tell the asp.net mvc to look up at embedded resource, first we need to define a VirtualFile (System.Web.Hosting.VirtualFile). VirtualFile class can act as a “false” view file. When accessed, it can read the embedded resource file and return it instead of serving the asp.net mvc engine with physical file. Next step, we need to supply asp.net mvc with VirtualPathProvider class that can direct the engine into finding and serving the VirtualFile instead of physical file. Both of the files that will make it possible to serve asp.net views from source other than physical file.

Here’s the code for both class (with supporting class):

    public class EmbeddedResourcePathConfiguration
        public EmbeddedResourcePathConfiguration(string rootNameSpace, string viewFolderName, Assembly resourceAssembly)
            this.RootNameSpace = rootNameSpace;
            this.ViewFolderName = viewFolderName;
            this.ResourceAssembly = resourceAssembly;
        public string RootNameSpace { get; set; }
        public string ViewFolderName { get; set; }
        public Assembly ResourceAssembly { get; set; }
        public string ViewNameSpace
                return RootNameSpace + "." + ViewFolderName;


    public class EmbeddedResourceNameProvider
        private EmbeddedResourcePathConfiguration configuration = null;
        public EmbeddedResourcePathConfiguration Configuration
            get { return configuration; }
            set { configuration = value; }

        public string GetResourceName(string virtualPath)
            var resourcename = virtualPath

            return resourcename;

    public class EmbeddedVirtualFile : VirtualFile
        public EmbeddedVirtualFile(string virtualPath, EmbeddedResourcePathConfiguration configuration)
            : base(virtualPath)
            this.configuration = configuration;
            EmbeddedResourceNameProvider.Configuration = configuration;
        private EmbeddedResourcePathConfiguration configuration = null;

        EmbeddedResourceNameProvider embeddedResourceNameProvider = new EmbeddedResourceNameProvider();
        public EmbeddedResourceNameProvider EmbeddedResourceNameProvider
            get { return embeddedResourceNameProvider; }
            set { embeddedResourceNameProvider = value; }

        public override Stream Open()
            string resourcePath = EmbeddedResourceNameProvider.GetResourceName(VirtualPath);
            return configuration.ResourceAssembly.GetManifestResourceStream(resourcePath);
    public class EmbeddedViewPathProvider : VirtualPathProvider
        EmbeddedResourceNameProvider embeddedResourceNameProvider = new EmbeddedResourceNameProvider();
        public EmbeddedResourceNameProvider EmbeddedResourceNameProvider
            get { return embeddedResourceNameProvider; }
            set { embeddedResourceNameProvider = value; }

        private EmbeddedResourcePathConfiguration configuration = null;
        public EmbeddedViewPathProvider(EmbeddedResourcePathConfiguration configuration)
            this.EmbeddedResourceNameProvider.Configuration = configuration;
            this.configuration = configuration;

        private bool IsVirtualFile(string virtualPath)
            return virtualPath.Contains(configuration.ViewNameSpace);

        private bool ResourceFileExists(string virtualPath)
            var resourcename = EmbeddedResourceNameProvider.GetResourceName(virtualPath);
            var result = resourcename != null && configuration.ResourceAssembly.GetManifestResourceNames().Contains(resourcename);
            return result;

        public override System.Web.Caching.CacheDependency GetCacheDependency(string virtualPath, System.Collections.IEnumerable virtualPathDependencies, DateTime utcStart)
            if (IsVirtualFile(virtualPath))
                return new System.Web.Caching.CacheDependency(configuration.ResourceAssembly.Location);
            return base.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);

        public override bool FileExists(string virtualPath)
            if (IsVirtualFile(virtualPath))
                bool exists = ResourceFileExists(virtualPath);
                return exists;
                return base.FileExists(virtualPath);

        public override VirtualFile GetFile(string virtualPath)
            if (IsVirtualFile(virtualPath))
                return new EmbeddedVirtualFile(virtualPath, configuration);
                return base.GetFile(virtualPath);

Register the path provider into applications

The last step is to register the path provider to application. You can use the following code at global.asax, inside Application_Start.

EmbeddedResourcePathConfiguration configuration =
                    new EmbeddedResourcePathConfiguration(
                        rootNameSpace: "HtmlViewTemplate",
                        viewFolderName: "Views",
                        resourceAssembly: Assembly.Load("HtmlViewTemplate"));
                HostingEnvironment.RegisterVirtualPathProvider(new EmbeddedViewPathProvider(configuration));

Framework development is hard

Note: I intended to make this article only as draft or brainstorming article, however my idea maybe useful for some of the reader. This article will lack supporting source and theory, and maybe having un-arranged topic. I’ll try to publish another article after some time after this to re-arrange the writing.

Have you ever tried to develop framework, or even as simple as code library? Is it easy? Is it hard? Well yeah, the answer is it depends. It depends based on the complexity and size of framework/library you develop. But I think that it is fairly easy to develop at start. It will get harder to develop when the framework is already large enough, especially modifying existing features.

I can’t imagine how hard the developer at .Net / C# is when developing new version.

Backward Compatibilty

It’s hard. Jon Skeet also say that backward compatibility is hard. I have developed a medium-sized framework for Asp.Net MVC server side for around 1 year. In that elapsed time span, I have made around three breaking changes. Without good architect / planner, the library will be likely have bad structure and need to be refactored much.

I don’t think that if asp.net still support backward compatibility with asp classic, it will still have the utilities and flexibility as it have now. What will happen if the new C# version does not consider backward compatibility? What powerful feature that can be introduced by the breaking change? Here I will say that “without backward compatibility, the new version of a framework should be much more powerful”.

Defining name, namespace categorization

Defining name is not easy. Often I don’t know how to name a specific class / operation. In a worse case, the class name will be very long to express the operation.

Categorizing the operation is even harder. Will it be put under Excel namespace? App namespace? Web namespace? Javascript? etc. Most of the time I refactor is because the incorrect namespace category / project placement.

Flexible / Parameters definition

Developing framework / library is not easy. Developing flexible library is even harder. Most of the time, the breaking change will happen at different parameter definition. Mostly can be handled using default parameter, while the other need to be added or modified, introducing breaking change.

Another problem during developing library is the amount of parameter required for an operation (function / method). Often we find that the operation need many parameters. That kind of structure is not recommended, because it will make the operation harder to use. Encapsulating the parameters into one class may be useful, but again it introduce another model. Moreover, many parameters usage is a sign of “god object“, which is hard to maintain.

Parameter initialization / life cycle

Parameter initialization is another pain. Many times I find the case where when I want to use object A in class X, it haven’t been fully initialized yet. Or worse, you can only use object A in class X after you do operation Z.

The setup + parameter structure

Despite the limitation, I like the idea in some of .Net’s library structure. XmlSerializer is one of them. The process that is needed to use XmlSerializer is: instantiate object, define setup, do operation (serialize). Inside the class, there exists some “setup” object, where you can modify to change the operation behavior, instead of passing all the setup objects yourself. Moreover, it has “default” setup parameter, in which you will need less effort rather than constructing the setup parameter down from zero.

It has limitation though, the “mutability”. The mutability at service object is bad. You cannot use the same object over and over again. One object is used one operation, unless the same setup is required at the operation. Don’t use the setup + parameter structure when you are using long-lasting object (such as static object).

Separate context class with service class

I am the follower or Anemic Domain Model pattern despite being classified as anti pattern. I think ADM with POCO class (DTO-style) really supporting SRP, instead using RDM, in which we can easily fall into the god object anti pattern. It’s not that I say RDM tend to violates SRP, however I find that in most case, it is easier for RDM to violates SRP rather than ADM’s antipattern bring cause.

That’s why I usually like to separate context class (as data model) with service class (the operation). The context is an object that hold all the data required during one “operation life cycle”. Example: AppContext hold all data required during application running. Setup class is a context, it holds all the data required during the class’s operation. In Asp.Net, RequestContext holds all data required during the web request.

Meanwhile service class hold almost no data and only responsible to process the request passed from parameter (in exception to the setup class). StringBuilder is one of them. I also like to separate entity (domain model) class with it’s operations. That way, I can easily develop more class to handle different business rules and cases.

The separation is intended to scope and encapsulate the operation / context. That scoping will be useful to make the class’s modification easier. Any modification happen at one service class won’t break other operation in other service class.

Don’t refer to static context directly

I admit, I also like to do something like this:

public void Do(){
    string userId = App.Context.Current.User.UserId;
    if(userId == "....") { /*the operation*/ }

It is a bad design in general, because we cannot use the service without the context. However, passing the context into parameter is out of question. It will increase operation complexity. However, you can separate the context into class’s property and do lazy loading for default context.

private App.Context context;
public App.Context Context{
    set { this.context = value; }
    get { return (this.context ? (this.context = App.Context.Current)); }

public void Do(){
    string userId = this.Context.User.UserId;
    if(userId == "....") { /*the operation*/ }

Now you can mock the context easily and provide it to the class before processing. And it’s testable now.


Framework development is hard.

DataBinding is Neat

Data binding is a nice feature and powerful. I am quoting what Martin Fowler has said in his article about state:

One copy of data lies in the database itself. This copy is the lasting record of the data, so I call it the record state. A further copy lies inside in-memory Record Sets within the application. Most client-server environments provided tools which made this easy to do. This data was only relevant for one particular session between the application and the database, so I call it session state. The final copy lies inside the GUI components themselves. This, strictly, is the data they see on the screen, hence I call it the screen state.

Data binding primarily used to solve the synchronization problem between state in GUI (screen state) with application memory state. Any change happen at GUI reflected to memory and vice versa. It is the ideal solution for developer who do not like to do anything twice or multiple times.

Why is databinding is an ideal solution for us developers?

  1. Less code for developers
    It is the absolute benefit for developers since less code means less work, less review and less debugging. As most of developer is often quoted with: It seems that perfection is attained not when there is nothing more to add, but when there is nothing more to remove. In rough understanding, it means faster development.
  2. Consistent
    The code used for handling data binding is same for entire system/framework. It means one solution for a case is also applicable for the same case in other place. Also in some other words, the consistency itself is DRY, since it follows “Every piece of knowledge must have a single, unambiguous, authoritative representation within a system”.
  3. Flexible
    A good databinding feature can give you more flexibility. You can do modification with the display easier and nice, with less code to do.
  4. Encourage Single Responsibility Principle
    It helps to decouple your viewmodel with your UI. Databinding can help to remove the responsibility to handle UI update from your viewmodel, thus encourage SRP.


Databinding can help you to solve synchronization problem between UI state and memory state, and a nice feature to have. If you are doing intensive data entry with updated UI here and there, it can provide you with flexibility and ease of use to freely modify the display.

But does it have any drawback aside from it’s powerful functionality?