Pull mass name list from database or in script? - oop

I need to fill an input box with a first name and last name. The user will press "Randomize" and it will pull a random first and last name and fill the inputs.
My question is I'm not sure if I should put the names in tables (firstNames, lastNames) or just store them in a javascript file and pull straight from that.
I'm trying to follow the Single Responsibility Principle so I'm inclined to choose the former, but then I have two more models, two more seeders, two more tables, and probably a class to pull all that together. And then do I fill from a CSV file or just from a manually populated seeder? It seems like a lot of work and extra files for a 1-time use.
I know I'll get crap for this being an opinion based question but there is no one or where else to ask.
Also if you know of a place to ask these kind of questions that won't get me ripped apart I'd appreciate that.

I would suggest using the Faker PHP library. That way you wouldn't have to create extra tables, models, or have to worry about finding yourself fake data.
To install it in your project, simply add the dependency in your composer.json file. and run a composer update.
"require-dev": {
"fzaninotto/faker": "1.3.*#dev"
},
Then you can use it to create fake first and last names for you (in your controller most likely)
$faker = Faker\Factory::create();
$firstName = $faker->firstName;
$lastName = $faker->lastName;
Edit:
To add your own names you can either edit or override the name provider file located here.

I would like to suggest Fakerino a new fake generator PHP library, with a modern approach, easy to extend with custom data, custom fake data class, or pre-configured groups of data.
https://github.com/niklongstone/Fakerino
<?php
include ('../Fakerino/vendor/autoload.php');
use Fakerino\Fakerino;
$fakerino = Fakerino::create();
echo $fakerino->fake('Surname')->toJson(); //["Donovan"]
echo $fakerino->fake('NameFemale'); //Alice
//with configuration
$fakerino = Fakerino::create('./conf.php');
print_r($fakerino->fake('fake1')->toArray());
/*
Array(
[0] => Arthur
[1] => Doyle
)
*/
//conf.php
<?php
$conf['fake'] = array(
'fake1' => array('NameMale', 'Surname' => null),
'fake2' => array('NameFemale', 'Surname' => null)
);

Related

Yii recognise timestamp column

I'm using giix to extend model (and crud) behavior. In this I would like to handle columns of type timestamp (that already exist in my model) specifically, rather like autoincrement fields are handled. (Ignored and not shown, that is.) However, there is no property $column->isTimestamp. I would like to add this somewhere, but I'm rather at loss what the best place for this would be. Do I put it in giix somewhere, or do I have to extend the column-baseclass?
Edit: I want to ignore them from every view, for every table. Since this is a lot of work, and it's something I always want, I'd like to automate it. Adapting the generators seems to make most sense, but I'm not sure what the best way to do it would be.
Here is the process:
Extend your database schema, if you are on MySQL it is CMysqlSchema.
Extend CMysqlColumnSchema and add a "isTimestamp" attribute.
In your CMysqlSchema sub-class extend createColumn and test for a timestamp, you'll see that Yii makes simple string comparisons here to set it's own flags. Set "isTimestamp" in your CMysqlColumnSchema here.
Tell Yii to use your schema driver like this in your components section in the config:
'db' => array(
'connectionString' => 'mysql:host=localhost;dbname=database',
'username' => '',
'password' => '',
'driverMap' => array('mysql' => 'CustomMysqlSchema'),
),
You will need to query the column schema, I've not used giix but find where it is generating the views, it should be looping through either the model attributes or the underlying table schema.
If it is looping through the schema:
//you can also ask Yii for the table schema with Yii::app()->db->schema->getTable[$tableName];
if ('timestamp' === $tableSchema->columns[$columnName]->dbType)
continue; //skip this loop iteration
If it loops over the attributes:
$dbType = Yii::app()->db->schema->getTable[$model->tableName]->columns[$modelAttribute]->dbType;
if ('timestamp' === $dbType)
continue; //skip this loop iteration

RoR: how to tell which params in a form have changed

In a Rails application, I have a particular form with many fields for editing a resource. Since I also want to log what was changed for this particular resource, I need to know which params changed.
Currently in this form, I have duplicated every field in the form with hidden field tags, so in the controller every field is compared to the corresponding hidden field to determine if the value was changed. But it's a LOT of work in the view and in the controller.
Being relatively new to Rails, I'm finding all kinds of Rails "magic" as I go along, so I wonder: does the framework provide a way to do this for me? Or is this pretty much the only way?
ActiveModel has exactly what you're looking for, take a look at the examples in the docs...
http://api.rubyonrails.org/classes/ActiveModel/Dirty.html
person = Person.find_by_name('Uncle Bob')
person.changed? # => false
person.name = 'Bob'
person.changed? # => true
person.name_changed? # => true
person.name_was # => 'Uncle Bob'
person.name_change # => ['Uncle Bob', 'Bob']
person.name = 'Bill'
person.name_change # => ['Uncle Bob', 'Bill']
You can try Dirty attributes for this task.
#post.attributes = params[:post]
#post.changed # or changes if you want to see what values on which was changed
More on that you can find by this link: http://ar.rubyonrails.org/classes/ActiveRecord/Dirty.html
Also if you want to use versioning or auditing, try this gems (best ones are: paper_trail, acts_as_audited, vestal_versions):
https://www.ruby-toolbox.com/categories/Active_Record_Versioning
https://www.ruby-toolbox.com/categories/Active_Record_User_Stamping

Can anyone explain how CDbCriteria->scopes works?

I've just checked the man page of CDbCriteria, but there is not enough info about it.
This property is available since v1.1.7 and I couldn't find any help for it.
Is it for dynamically changing Model->scopes "on-the-fly"?
Scopes are an easy way to create simple filters by default. With a scope you can sort your results by specific columns automatically, limit the results, apply conditions, etc. In the links provided by #ldg there's a big example of how cool they are:
$posts=Post::model()->published()->recently()->findAll();
Somebody is retrieving all the recently published posts in one single line. They are easier to maintain than inline conditions (for example Post::model()->findAll('status=1')) and are encapsulated inside each model, which means big transparency and ease of use.
Plus, you can create your own parameter based scopes like this:
public function last($amount)
{
$this->getDbCriteria()->mergeWith(array(
'order' => 't.create_time DESC',
'limit' => $amount,
));
return $this;
}
Adding something like this into a Model will let you choose the amount of objects you want to retrieve from the database (sorted by its create time).
By returning the object itself you allow method chaining.
Here's an example:
$last3posts=Post::model()->last(3)->findAll();
Gets the last 3 items. Of course you can expand the example to almost any property in the database. Cheers
Yes, scopes can be used to change the attributes of CDbCriteria with pre-built conditions and can also be passed parameters. Before 1.1.7 you could use them in a model() query and can be chained together. See:
http://www.yiiframework.com/doc/guide/1.1/en/database.ar#named-scopes
Since 1.1.7, you can also use scopes as a CDbCriteria property.
See: http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-named-scopes

Drupal: Display a list of contribution (posted content) for each user

I’m searching for a way to display on a member profile page, the number of contributions in some content types. Basically it has to display something like this:
Blog(10)
Articles(10)
Questions(19)
Comments(30)
Tips(3)
I’ve installed some different modules (like “user stats”) that I though could help me but haven’t been successful.
I’m wondering if it would be easiest just to hard-code it into my template file by starting taking the uid and just run some queries with the content types I want to display but I’m not sure on how to do that either.
Any help og suggestions would be very much appreciated.
Sincere
- Mestika
Edit:
I found a solution to do it manually with a query for each content type but I'm still very interested in a solution that's more elegant and smoother.
I use this code:
global $user;
$userid = $user->uid;
$blog_count = db_result(db_query("SELECT COUNT(0) AS num FROM {node} n where n.type = 'blog' AND status = 1 AND n.uid = {$userid}"));
If you are using the core Profile module, you could use something like below. It will show the nodes created by the user whose profile is being viewed. As an added benefit, it only needs to execute one custom database query.
Insert this snippet into template.php in your theme's folder and change "THEMENAME" to the name of your theme:
function THEMENAME_preprocess_user_profile(&$variables) {
// Information about user profile being viewed
$account = $variables['account'];
// Get info on all content types
$content_types = node_get_types('names');
// Get node counts for all content types for current user
$stats = array();
$node_counts = db_query('SELECT type, COUNT(type) AS num FROM {node} WHERE status = 1 AND uid = %d GROUP BY type', $account->uid);
while ($row = db_fetch_array($node_counts)) {
$stats[] = array(
'name' => $content_types[$row['type']],
'type' => $row['type'],
'num' => $row['num'],
);
}
$variables['node_stats'] = $stats;
}
Now, in user-profile.tpl.php can add something similar to:
// If user has created content, display stats
<?php if (count($node_stats) > 0): ?>
// For each content type, display a DIV with name and number of nodes
<?php foreach ($node_stats as $value): ?>
<div><?php print $value['name']; ?> (<?php print $value['num']; ?>)</div>
<?php endforeach; ?>
// Message to show for user that hasn't created any content
<?php else: ?>
<?php print $account->name; ?> has not created any content.
<?php endif; ?>
This is just a general idea of what you can do. You can also add restrictions to the content types you look for/display, check permissions for users to see these stats, use CSS to change the look of the stats, etc.
If you are using Content Profile, you could use THEMENAME_preprocess_node() and check that the node is a profile node before executing this code.
Given your simple requirement and the fact that you have the SQL statement in-hand, I'd say just use that. There's no reason to add yet another module to your site and impact it's performance for the sake of a single query.
That said, from a "separation of concerns" standpoint, you shouldn't just drop this SQL in your template. Instead, you should add its result to the list of available variables using a preprocess function in your template.php file, limiting its scope to where you need it so you're not running this database query on any pages but the appropriate profile page.

how to represent trees and their content in MySQL?

I need to be able to store something like this:
where the green is a template type, the gray is a field container type, and the white is field. (That being, a field has a label and some text, both mediumtext for simplicity; and a field container can store other field containers or text, and a template is a top-level field.)
Now, let's say I want to allow users to create any number of these structures, but it is unlikely to be more than say 10. And, of course, we need to be able to link data to it.
This is all to be able to store in a database an associative array that looks for the above like, in pseudo code:
my_template = {
page_info => { description => 'hello!!!' },
id => 0,
content => { background_url => '12121.jpg', text => ...
}
Having an easy way to add a field to all data using the template when the template changes (say, we add a keywords to page_info) would be a big plus.
I can't figure this out at all, thanks a lot!
There are several different ways to store heirarchical data structures (trees) in MySQL. You can for example choose:
Adjacency list
Nested sets
Path enumeration
Closure table
See Bill Karwin's presentation for more details on the pros and cons of each.