Is the state design pattern overkill for a PHP form? - php

I have a page that, when accessed displays a table of information related to a video:
Embed code
Title
Description
Current gallery
Thumbnail image
This information is read-only when the page is first accessed.
There is a select menu that has the following options:
Edit Description
Create Thumbnail (Upload/Replace)
Edit embed code
Change Gallery
Delete video
When the user selects an option, the same initial table of data is displayed, but the relevant form input is displayed where necessary.
For example, if "Edit Description" is selected, the page reloads and the description text is replaced with a text input. If "Create Thumbnail" is selected, then a file upload input is displayed.
The idea is to display all of the information together but to limit how much can be edited at a time.
I know the state pattern is a possible solution, since each piece of data can be in atleast one of two states:
Display State
Form input state
But, my question is, would using the state pattern be overkill?
At the moment, each time the page is accessed, each part of the form decides with a switch statement whether it should be in 'display' or 'input' state and then acts accordingly. I wonder if implementing the state pattern design would make altering the form and creating similar forms easier down the road.
Thanks!

No, the state design pattern isn't overkill. It's probably a very good choice of algorithm for handling such a complex interface. I've used state engines in PHP several times; it helps you think creatively about the problem and you often get a bonus in flexibility.
I wish more programmers knew of such things.

The more I use design patterns, including the State pattern in PHP, the more I'm convinced that they save time. Initially, it may take longer to develop, but not much longer. However, when it comes to change and update, they save huge amounts of time. Your code is better organized, clearer and less likely to through a bomb into your code that you get with the tight binding outside of design patterns. I've done several PHP design patterns at php5dp.com, but, nothing in a State dp.

Related

How to make an admin page to modify/add to a list, create new web pages, etc

I want to add functionality to a website I am building for a client that allows him to log on to a secure page and add new job listings. He will be the only one modifying this so I don't need to worry about concurrent access or anything like that. At this point I don't even have a database set up for him but I understand that might need to be implemented soon, for other features if not this one.
He doesn't have any knowledge of HTML so I can't just create a template job posting and have him manually fill in the information (although that is also unprofessional, I suppose.) I was planning on just making a simple php/html page where he could put the title of the job along with all details through submission of a form. Once I have that, though, I don't know how to deal with adding that job title to a list of current job postings and also have that link to a new page with all the details of the job.
My memory from early undergraduate classes are hinting that the adding jobs to a list would be object-oriented. However, I can also see something where I would just add the title to an array which the list then dynamically filled from.
Another recommendation I have received is to look into implementing a django/python solution. The problem is I have about a week to work on this and I ahve no python experience. If that is something that would be possible to learn and implement in that time, I will go for it. I just don't want to waste time on something that takes a week or two to learn and then still have nothing implemented.
Basically, I would appreciate a point in the right direction and some reassurance that I am considering all possibilities. If it would be easier to implement some kind of simple wiki, that is another option as well.
Do any of these ideas sound like the right choice? Is there anything I am missing?
I apologize if this is a trivial question but I have stumped myself and would appreciate any help you can offer.
A possible and easy solution would be using an appropriate CMS module, like Job Manager or Resume Submissions and Job Posting for WordPress. I haven't tested them personally, but they should handle everything for you through a Web interface, no coding needed (you should just adapt the WordPress CSS to match the existing client's Website style).
For reference, here's what I would have done in case no such CMS module existed.
Create a database with a table that will hold all job postings. The table should have the following columns: id, title, description, validityDate (names are self-explanatory). Add more if appropriate.
Write a script that queries the database for all current job postings using the following query: SELECT id, title FROM postings WHERE validityDate >= NOW(). To manage database connections, use the PHP PDO extension (look at its page on the PHP manual website for examples). This will return a list of all current job postings. For each result, let the script output HTML code like this: echo "$title<br />$description";, where $id, $title and $description are the variables holding the ID, title and description of the current record.
Write the post.php script that will fetch the details of the job posting with the ID specified in the id parameter.
Write another script where the client will input the details for a new posting into a form. After submission, the script should just insert the data into the table.

A better alternative to my approach (Symfony 1.4 modules)

In my quest for perfection and minimalism, I post this question here to you guys, seeking if there is a better and more alternative option than the one I have.
I have a module with two different templates. Essentially the first is a quiz template, the second is a page that displays the results of the quiz. The quiz is a form whereas the results page is not. On my quiz page, the action for the form is essentially 'module/quizResults?id='.$quizId
Now for the quiz action, I do a db query to retrieve the set of questions that belong to the quiz and then when the post takes place the action that is being called is that of quizResults, out here I must compare the answer options of my user against the correct answer options for the questions of a quiz. Essentially, I have to again query the db to retrieve the set of questions for the quizzes in another db. I feel this is a slight overkill and I am irked.
I think there can be better solutions. I can post back to the same quiz page, but then that demands more complexity on the template as well as the action making things a little murkier.
Any alternatives?
Thanks
There are a few options you could implement to do what your asking, but you need to ask yourself will the added complexity outweigh the minor performance gains, especially if the queries are optimized.
Option #1: Session
When you load the questions from the quiz action, you could add the questions to the user's session, then when the user posts the quiz for the results, simply refer to the questions stored in session.
Option #2: Memcached
Same as above, but instead of storing the questions to the user session, you could store the questions into memcache, so when you calculate the results, instead of making another database query, you pull the questions from the cache layer instead.
You're trying to solve this the wrong way.
Performance is absolute no issue here. But what is an issue is programmer performance. If you have to manually craft each query and pass all the right variables along it's going to take a lot of your time. What you need is a framework that will allow you to build the necessary logic in a quicker way. If you know how to do this perfectly you will make a lot of money, until then you'll have to scratch along just like the rest of us :P
Assuming the submission page should display all-good if all correct, or the incorrect ones if not, I would write a myprojectQuestionValidator and use that in my question form, one for each question/answer. The validator can then check each answer against the correct one in the database. Agreed with Frits, don't worry about performance - that's premature optimization IMO. Break the app into conceptual components, and worry about optimization when you need to.

Technique for multiple users on same datasets

This is more a learning question than coding, but I'm certain it's a common issue for anyone developing administration systems or applications in php/mysql/js etc.
I've developed quite a complex application that lets users upload images, and define hotspots in them with associated actions. The images are stored in a table, and the actions in another, with json data for every action in a text field. It's a magazine style format that is used by a custom reading application. However, like I say, the problem is generic.
Basically, my fear is that if someone is editing the same image and set of actions at the same time, and they both submit changes, or if it was edited by someone else then there's a whole series of structures that potentially will fail on submission.
I don't want to implement a locking system, as the system is very wide ranging (links to other images, etc), and I think it's a bit ugly. I saw this link (MSDN Multi-tenant architecture article) in another question, but it seems a little overwhelming and specialised for sql server.
So - what are the terms for data and system architecture here that I can investigate, or are there some good articles to do with this topic that people can recommend? Specifically for php/web world would be great!
--
I'm still looking for good responses on this question. Found out meanwhile that the general term is 'Concurrency', but technique is the important thing :)
First
ALTER TABLE tablename ADD COLUMN changecount BIGINT NOT NULL DEFAULT 0;
for all relevant tables. Then whenever you want to submit a change, use not only
UPDATE tablename SET whatever WHERE id=whatever
but
UPDATE tablename SET whatever, changecount=changecount+1 WHERE id=whatever AND changecount=the_changecount_you_remembered_from_loading_the_object
now if a user submits a change, it will update the changecount - another user submitting a change to the same object, but loaded from older state, can be told "another user has just changed blah blah"

Multi-language social website - Database driven?

To store multi language content, there is lots of content, should they be stored in the database or file? And what is the basic way to approach this, we have page content, reference tables, page title bars, metadata, etc. So will every table have additional columns for each language? So if there are 50 languages (number will keep growing as this is a woldwide social site, so eventual goal is to have as many languages as possible) then 50 extra columns per table? Or is there a better way?
There is a mixture of dynamic system and user content + static content.
Scalability and performance are important. Being developed in PHP and MySQL.
User will be able to change language on any page from the footer. Language can be either session based or preference based. Not sure what is a better route?
If you have a variable, essentially unknown today number of languages, than this definately should NOT be multiple columns in a record. Basically the search key on this table should be something like message id plus language id, or maybe screen id plus message id plus language id. Then you have a separate record for each language for each message.
If you try to cram all the languages into one record, your maintenance will become a nightmare. Every time you add another language to the app, you will have to go through every program to add "else if language=='Tagalog' then text=column62" or whatever. Make it part of the search key and then you're just reading "where messageId='Foobar' and language=current_language", and you pass the current language around. If you have a new language, nothing should have to change except adding the new language to the list of valid language codes some place.
So really the question is:
blah blah blah. Should I keep my data in flat files or a database?
Short answer is whichever you find easier to work with. Depending on how you structure it, the file based approach can be faster than the database approach. OTOH, get it wrong and performance impact will be huge. The database approach enforces more consistent structure from the start. So if you make it up as you go along, then the database approach will probably pay off in the long run.
eventual goal is to have as many languages as possible) then 50 extra columns per table?
No.
If you need to change your database schema (or the file structure) every time you add a new language (or new content) then your schema is wrong. If you don't understand how to model data properly then I'd strongly recommend the database approach for the reasons given.
You should also learn how to normalize your data - even if you ultimately choose to use a non-relational database for keeping the data in.
You may find this useful:
PHP UTF-8 cheatsheet
The article describes how to design the database for multi-lingual website and the php functions to be used.
Definitely start with a well defined model so your design doesn't care whether data comes from a file, db or even memCache or something like that. Probably best to do a single call per page to get an object that contains all the fields for that single page, rather than multiple calls. The you can just reference that single returned object to get each localised field. Behind the scenes you could then code the respository access and test. Personally I'd probably go the DB approach over a file - you don't have to worry about concurrent file access and it's probably easier to deploy changes - again you don't have to worry about files being locked by reads when you're deploying new files - just a db update.
See this link about php ioc, that might help you as that would allow you to abstract from your code what type of respository is used to hold the data. That way if you go one approach and later you want to change it - you won't have to do so much rework.
There's no reason you need to stick with one data source for all "content". There is dynamic content that will be regularly added to or updated, and then there is relatively static content that only rarely gets modified. Then there is peripheral content, like system messages and menu text, vs. primary content—what users are actually here to see. You will rarely need to search or index your peripheral content, whereas you probably do want to be able to run queries on your primary content.
Dynamic content and primary content should be placed in the database in most cases. Static peripheral content can be placed in the database or not. There's no point in putting it in the database if the site is being maintained by a professional web developer who will likely find it more convenient to just edit a .pot or .po file directly using command-line tools.
Search SO for the tags i18n and l10n for more info on implementing internationalization/localization. As for how to design a database schema, that is a subject deserving of its own question. I would search for questions on normalization as suggested by symcbean as well as look up some tutorials on database design.

Realtime MySQL search results on an advanced search page

I'm a hobbyist, and started learning PHP last September solely to build a hobby website that I had always wished and dreamed another more competent person might make.
I enjoy programming, but I have little free time and enjoy a wide range of other interests and activities.
I feel learning PHP alone can probably allow me to create 98% of the desired features for my site, but that last 2% is awfully appealing:
The most powerful tool of the site is an advanced search page that picks through a 1000+ record game scenario database. Users can data-mine to tremendous depths - this advanced page has upwards of 50 different potential variables. It's designed to allow the hardcore user to search on almost any possible combination of data in our database and it works well. Those who aren't interested in wading through the sea of options may use the Basic Search, which is comprised of the most popular parts of the Advanced search.
Because the advanced search is so comprehensive, and because the database is rather small (less than 1,200 potential hits maximum), with each variable you choose to include the likelihood of getting any qualifying results at all drops dramatically.
In my fantasy land where I can wield AJAX as if it were Excalibur, my users would have a realtime Total Results counter in the corner of their screen as they used this page, which would automatically update its query structure and report how many results will be displayed with the addition of each variable. In this way it would be effortless to know just how many variables are enough, and when you've gone and added one that zeroes out the results set.
A somewhat similar implementation, at least visually, would be the Subtotal sidebar when building a new custom computer on IBuyPower.com
For those of you actually still reading this, my question is really rather simple:
Given the time & ability constraints outlined above, would I be able to learn just enough AJAX (or whatever) needed to pull this one feature off without too much trouble? would I be able to more or less drop-in a pre-written code snippet and tweak to fit? or should I consider opening my code up to a trusted & capable individual in the future for this implementation? (assuming I can find one...)
Thank you.
This is a great project for a beginner to tackle.
First I'd say look into using a library like jquery (jquery.com). It will simplify the javascript part of this and the manual is very good.
What you're looking to do can be broken down into a few steps:
The user changes a field on the
advanced search page.
The user's
browser collects all the field
values and sends them back to the
server.
The server performs a
search with the values and returns
the number of results
The user's
browser receives the number of
results and updates the display.
Now for implementation details:
This can be accomplished with javascript events such as onchange and onfocus.
You could collect the field values into a javascript object, serialize the object to json and send it using ajax to a php page on your server.
The server page (in php) will read the json object and use the data to search, then send back the result as markup or text.
You can then display the result directly in the browser.
This may seem like a lot to take in but you can break each step down further and learn about the details bit by bit.
Hard to answer your question without knowing your level of expertise, but check out this short description of AJAX: http://blog.coderlab.us/rasmus-30-second-ajax-tutorial
If this makes some sense then your feature may be within reach "without too much trouble". If it seems impenetrable, then probably not.

Categories