Generating pages from a database - database

I'm looking for some help understanding how to generate pages from a database to create a catalog of items, each with different URLs. All I can seem to find through google are products that will do this for me, or full e-commerce solutions. I don't want a shopping cart! Just an inventory.
Also, perhaps someone could recommend their favorite/the best simple login solution.
Thank you so much for your time and any help, suggestions, comments, solutions.

I just posted a thorough solution to another question that is very closely-related to this question. I'll re-post it here for your convenience:
I would suggest using some of the MVC (Model, View, Controller) frameworks out there like KohanaPHP. It is essentially this. You're working in a strictly Object-Oriented environment. A simple page in Kohana, build entirely from a class would look like this:
class Home_Controller extends Controller
{
public function index()
{
echo "Hello World";
}
}
You would then access that page by visiting youur url, the class name, and the method name:
http://www.mysite.com/home/ (index() can be called after home/, but it's implicit)
When you start wanting to bring in database-activity, you'll start working with another Class called a Model. This will contain methods to interact with your database, like the following:
class Users_Model extends Model
{
public function count_users()
{
return $this->db->count_records('users');
}
}
Note here that I didn't write my own query. Kohana comes with an intuitive Query Builder.
That method would be called from within your Controller, the first class that we mentioned at the beginning of this solution. That would look like this:
class Home_Controller extends Controller
{
public function index()
{
$usersModel = new Users_Model;
$userCount = $usersModel->count_users();
echo "We have " . $userCount . " users!";
}
}
Eventually, you'll want more complicated layouts, which will involve HTML/CSS/Javascript. At this point, you would introduce the "Views," which are just presentation layers. Rather than calling echo or print from within the Controller, you would load up a view (an HTML page, essentially) and pass it some variables:
class Home_Controller extends Controller
{
public function index()
{
$myView = new View("index");
$usersModel = new Users_Model;
$userCount = $usersModel->count_users();
$myView->userCount = $userCount;
$myView->render(TRUE);
}
}
Which would load the following "View"
<p>We have <?php print $userCount; ?> users!</p>
That should be enough to get you started. Using the MVC-style is really clean, and very fun to work with.

There's a lot of tools out there for generating a web interface around a data model. I find Django pretty easy to use. Based on its popularity, I'm sure that Ruby on Rails is another viable option.

Related

How to dynamize cucumber value and pass that into the login page

How to dynamize cucumber value and pass that into the login page, for example:
If I use Adam in the cucumber scenario then it should automatically use adam login details and other information and if i use another name it should use that person's information. So i do not have to manually enter it in every step defination. How Can i achieve it?
Scenario: Add an item to shopping bag to place the order using mastercard
Given that "Adam" is logged in to his account
When he searches and adds an item from "men" section to his shopping bag
Then he can place the order
export class LoginUser implements Task {
static called(name: string): LoginUser {
return new LoginUser(name);
}
performAs(actor: PerformsTasks): PromiseLike<void> {
return actor.attemptsTo(
Click.on(homePageElementsMap.lnk_login),
Enter.theValue('test#test.com').into(loginPageElementsMap.txt_login_email),
Enter.theValue('password111').into(loginPageElementsMap.txt_login_pwd),
Click.on(loginPageElementsMap.btn_login)
);
}
constructor(private name: string) {
}
}
disclaimer: this is a java answer, I misread the tag. I am sure you can something similar for js.
For our tests we have a variety of users as well and we use a java class with userdata for this, set up as maps.
We pass the value to a static method public Map<String, String> getUserData(String username) which contains a switch for the variety of users we have, each user is given a map of data we want to use in the tests. The users each have a private Map in the class containing login information.
Of course, there are more scalable ways, this one just gives us the flexibility of a single public getUserData(userName) and behind this we can do with the storage whatever we want.
Short answer: static java code containing user information for a variety of usernames.
Is this the only way to do it? - http://docs.behat.org/en/v2.5/guides/1.gherkin.html

Merging two database tables into a single Vaadin Treetable

TL;DR: How do I combine info from two database tables into a Vaadin Treetable (or, when Vaadin 7.5 is released, a heirarchical Grid)?
I have a Java Swing desktop application that does this currently, albeit probably very ineffeciently with ArrayLists of Java Beans that updates from the SQL Server every 30 seconds. Well, I'm now attempting to port this desktop app over to a Vaadin web app. The desktop app has login capabilities and I'll eventually worry about doing the same for the web app, but for now, I just want to try and get the most basic part of this web app working: The Treetable. Or, hopefully soon, a heirarchical Grid.
To help illustrate what I'm aiming for, I'll try and post an image I created that should show how the data from the two tables needs to merge into the treetable (using a partial screenshot of my existing desktop app):
I am well aware of how to use the JOIN command in SQL and I've briefly read about Referencing Another SQLContainer, but I'm still in the early stages of learning Vaadin and still trying to wrap my head around SQLContainer, FreeformQuery, and how I need to implement FreeformStatementDelegate for my project. Not to mention that I'll need to implement checkboxes for each row, as you can see in that photo, so that it updates the database when they are clicked. And a semi-checked state for the checkbox would be necessary for Jobs that have more than one OrderDetail item wherein only some of those OrderDetail items are completed. To get that working for my Java Swing program, I had to lean on an expert Java developer who already had most of the code ready, and boy, is it super-complicated!
If anyone can give me a high-level view of how to accomplish this task along with some examples, I would be indebted. I totally understand that I'm asking for a great deal here, and I'm willing to take it slow, step-by-step, as long as you are. I really want to fully understand this so I'm not just copy-pasting code without thinking.
I have never used SQLContainer so this might not be the answer you want. I just had a quick look at SQLContainer and I'm not sure if it will serve your purpose. For a TreeTable you will need a Container Implementing the Container.Hierarchical interface or the table will put a wrapper around it and you have to set the parent-children relations manually. You probably could extend SQLContainer and implement the methods from Container.Hierarchical in that class but this might get complicated.
In your situation I think I'd go with implementing my own Container, probably extending AbstractContainer, to get the listener code for free, and implementing Hierarchical. There are quite some methods to implement, I know, and so this will need some time, but most methods are quickly implemented and you can start with the basic methods and add more interfaces (Ordered, Sortable, Indexed, Filterable, Collapsible,...) later.
If done properly you'll end up with with easy readable code that can be extended in the future without to much trouble and you will not depend on future versions of SQLContainer.
Another good thing is that you'll learn a lot about the data structures (Container, Item, Property) used in vaadin. But as I said I don't really know SQLContainer so maybe there will be a better answer telling you that it is easy with the SQLContainer
For the Checkbox feature you could go display the name/product property as a CheckBox. With Icon and Caption it looks almost like you want it. See http://demo.vaadin.com/sampler/#ui/data-input/other/check-box and set an Icon. The semi-checked state could be done with css.
Hope this helps you finding the right solution for your task.
I'll admit that I'm a beginner with vaadin myself and there may be much better ways of doing this, but here's something I've mocked up which seems to work. It doesn't do everything you need but it might be a base to start from. Most importantly, for changes to be saved back into the database you'll need to update the SQLContainers when something in the container is changed.
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.util.HierarchicalContainer;
import com.vaadin.data.util.sqlcontainer.SQLContainer;
#SuppressWarnings("serial")
public class TwoTableHierarchicalContainer extends HierarchicalContainer {
private SQLContainer parentContainer;
private SQLContainer childContainer;
private String parentPrimaryKey;
private String childForeignKey;
public TwoTableHierarchicalContainer(SQLContainer parentContainer, SQLContainer childContainer,
String parentPrimaryKey, String childForeignKey) {
this.parentContainer = parentContainer;
this.childContainer = childContainer;
this.parentPrimaryKey = parentPrimaryKey;
this.childForeignKey = childForeignKey;
init();
}
private void init() {
for (Object containerPropertyIds : parentContainer.getContainerPropertyIds()) {
addContainerProperty(containerPropertyIds, Object.class, "");
}
for (Object containerPropertyIds : childContainer.getContainerPropertyIds()) {
addContainerProperty(containerPropertyIds, Object.class, "");
}
for (Object itemId : parentContainer.getItemIds()) {
Item parent = parentContainer.getItem(itemId);
Object newParentId = parent.getItemProperty(parentPrimaryKey).getValue();
Item newParent = addItem(newParentId);
setChildrenAllowed(newParentId, false);
for (Object propertyId : parent.getItemPropertyIds()) {
#SuppressWarnings("unchecked")
Property<Object> newProperty = newParent.getItemProperty(propertyId);
newProperty.setValue(parent.getItemProperty(propertyId).getValue());
}
}
for (Object itemId : childContainer.getItemIds()) {
Item child = childContainer.getItem(itemId);
Object newParentId = child.getItemProperty(childForeignKey).getValue();
Object newChildId = addItem();
Item newChild = getItem(newChildId);
setChildrenAllowed(newParentId, true);
setParent(newChildId, newParentId);
setChildrenAllowed(newChildId, false);
for (Object propertyId : child.getItemPropertyIds()) {
#SuppressWarnings("unchecked")
Property<Object> newProperty = newChild.getItemProperty(propertyId);
newProperty.setValue(child.getItemProperty(propertyId).getValue());
}
}
}
}

Calling a model method from the controller in CakePHP

Is there no way to access a Model instance as an object (as opposed to as an array) within a Model method in CakePHP? As a super-simplified example, my instinct tells me it ought to be possible to do something like this:
Bird.php
...
public function specialName()
{
$name = $this->name;
return "Oh wow! It's ".$name;
}
If I call this method from my BirdController.php like so:
public function view($id) {
if (!$id) {
throw new NotFoundException(__('Invalid bird'));
}
$this->Bird->id = $id;
$this->set('results', $this->Bird->specialName());
}
... then it displays in the view file as "Oh wow! It's Bird" rather than "Oh wow! It's Freddy" (i.e. the name of the model, not the name of the model instance).
I've tried variations on this general approach, to no avail. It seems I must access the information via an array, like so:
Bird.php
...
public function specialName($id)
{
$data = $this->findById($id);
$name = $data['Bird']['name'];
return "Oh wow! It's ".$name;
}
This seems WAY over-complicated to me. What am I missing? Ultimately I want to be able to access dependent models in my model function, e.g. get all of the associated Bird->Subspecies. It seems like this would be much easier to do working with objects.
If you would have read the documentation about models you would know that Model::$name is the name of the model. There is also Model::alias which is the name of the model when it is accessed trough associations and the association is named different than the model name.
Cakes ORM does not return results as data objects, 3.0 will do that. Most easy way to return a specifc field right now is to do this in a model:
public function specialName($id) {
$this->id = $id;
return $this->field('name');
}
Also the "Oh wow..." should go to the view where you would echo the name that you set as $result.
If you want data objects, I know there is a plugin, a behaviour that will turn the result sets into data objects. Just google it.
Ultimately I want to be able to access dependent models in my model
function, e.g. get all of the associated Bird->Subspecies.
Did you read the book? See this section. With containable you can control what exactly you want to fetch from the associated models.
I recommend you to do the blog tutorial first to get an idea of the basics of how CakePHP works.

Multilanguage database management with Laravel

I'm creating an app with a backend in Laravel. The backend needs to manage a collection of objects which are downloaded to the app. The objects must be localised depending on the device language.
Is there a simple way to do this in Laravel? Perhaps an eloquent or Laravel-plugin? I'd like to avoid writing the localisation support myself.
(The built in localisation in Laravel is only for the interface, it doesn't support Eloquent objects)
You will need to write that on your own. First you will have to model your database tables to support multilanguage content and then in your model you will be able to say something like:
class Content extends Eloquent
{
public function scopeEnglish($query)
{
return $query->where('language', '=', 'en');
}
public function scopeSpanish($query)
{
return $query->where('language', '=', 'es');
}
}
class Post extends Eloquent
{
public function content()
{
return $this->hasMany('Content');
}
}
and then you can use it like:
$englishContent = Posts::find($id)->content->english()->get();
$spanishContent = Posts::find($id)->content->spanish()->get();
Glad To Help's answer seems perfect for multilingual site's with many languages.
I've found out that it's kind of clunky to do that when your site has just two/three languages.
What I've done is having two columns for each translatable fields.
for the title attribute I have in the database title_en and title_es.
After that, in the controller just set this method to do an automated translation.
public function getTitleAttribute()
{
$locale = App::getLocale();
$column = "title_" . $locale;
return $this->{$column};
}
Now when you call Post::find($id)->title it will automatically get the one for the current language.
Hope it helps.
Cheers!
I did similar but more universal
Schema::create('index', function(Blueprint $table) {
$table->increments('id');
$table->string('title_uk');
$table->string('title_ru');
$table->string('title_en');
$table->string('heading_uk');
$table->string('heading_ru');
$table->string('heading_en');
$table->string('photo');
$table->timestamps();
});
The model
public function TextTrans($text)
{
$locale=App::getLocale();
$column=$text.'_'.$locale;
return $this->{$column};
}
Now I for each language version as well as for each field will not prescribe a specific function, and cause all this:
$text=Index::find('1');
$text->TextTrans('title');
$text->TextTrans('heading');
There are some translation packages for Eloquent models and static language resources. You can combine them, it's up to your scenario.
These packages might be useful when you just want to translate your resources or outsource translation to 3rd parties (like customer or content creator) via extranet (kinda front-end), so these are storing your translation files in database:
https://github.com/barryvdh/laravel-translation-manager
https://github.com/joedixon/laravel-translation
In order to make your Eloquent model multilanguage, store it as JSON array. If you are creating a sort of CMS like application, you will need multilingual title or content body. Following packages might help to achive this:
https://github.com/Astrotomic/laravel-translatable
https://github.com/spatie/laravel-translatable
Following the #user1067281 answer I found a great advanced tutorial for multi languages site.
You should totally check this out: https://medium.com/laravel-4/26cdc75e4810

Different data sets per subdomain in Cakephp?

I am writing a personal bookmarks application and am looking for a way to have totally different content between subdomains.
I have written the application and it works fine, but have yet to implement multiple collections. I have the following models:
Tag (unused so far)
Bookmark
Subject
Bookmarks are categorized in subjects and I'm planning to allow tagging in the future and see if that helps me manage my bookmarks more easily.
The current problem I have is that I'd like to separate bookmarks as a whole. I want to use subdomains like webdevelopment.bookmarks.local, languages.bookmarks.local, linux.bookmarks.local that work with an entire own set of domains and bookmarks.
I am considering adding a new model called Set (short for "bookmark sets") and defining sets based on the subdomain.
According to that plan I'd have to rewrite all $this->...->find-queries in the entire App to contain the condition "set_id" = $SubdomainBasedSetid".
While it wouldn't be that much work, I was wondering if it could be done smarter, maybe that Cake would only see the relevant bookmark set per subdomain.
well, your solution is right. But instead of using subdomains, you can use prefix, so you don't have check and set yourself. Since you use subdomains, I assume that these sets are fixed or rarely change. So you don't really need a sets table, just use the set name directly in your bookmark record, so you don't have to convert between name and id.
According to that plan I'd have to rewrite all $this->...->find-queries in the entire App to contain the condition "set_id" = $SubdomainBasedSetid".
As all models extend AppModel, it is possible to edit all queries there before they happen (ie. DRY). :)
// app/app_model.php
class AppModel extends Model {
public function beforeFind($queryData) { // old query
// make changes
return $queryData; // new query
}
However, if you don't want this functionality for all models (or even if you do for now), a better place might be a behavior as this allows you to pick and choose where and when it is loaded:
// app/models/behaviors/subdomain.php
class SubdomainBehavior extends ModelBehavior {
protected $_defaults = array('field' => 'Site.subdomain');
public function setup(&$model, $config = array()) {
$this->settings[$model->alias] = array_merge($this->_defaults, $config);
}
public function beforeFind(&$model, $queryData) {
$domain = $_SERVER['SERVER_NAME'];
$subdomain = substr($domain, 0, strpos($domain, "."));
$queryData['conditions'][$this->settings['field']] = $subdomain;
return $queryData;
}
}
// app/app_model.php
class AppModel extends Model {
$actsAs = array('Subdomain' => array('field' => 'Set.slug'));
}
Tag (unused so far)
To save reinventing the wheel, you may want to look at CakeDC's tags and utils plugins (the latter contains SluggableBehavior which will help with generating friendly URL parts, such as the subdomains).

Resources