Default Criteria For Active Record - yii

I have a following question about the best practice for ActiveRecord usage.
My case:
I have a User model which is a normal CActiveRecord.
In many cases I want to have lists of "active" users, defined in the database by WHERE condition "is_active = 1". Besides I want functions find(), findByAttributes(), findByPk() etc. to return the result only if the user is active (for example in "Password request" scenario).
I can always apply this WHERE condition explicitly before using find() functions but I'm searching a way to implement it with less code.
I came to the idea of creating a child class called UserActive and change its constructor like this:
function __construct($scenario='insert') {
parent::__construct($scenario);
$criteria = new CDbCriteria();
$criteria->condition = "is_active = 1";
$this->setDbCriteria($criteria);
}
But I'm not sure if this is a good practice to do this (Since CActiveRecord's constructor asks "Do NOT override the constructor unless it is absolutely necessary!"). Can anyone give advices for this situation?

Try this in your model.
public function defaultScope() {
return array(
'condition'=>'is_active = 1',
);
}
Or define other scope
Yii - using relations with scopes defined in the relation

That's right, you should never override __construct().
You can use model scopes for that. See http://www.yiiframework.com/doc/guide/1.1/en/database.ar#named-scopes

Related

what is the difference with these query classes in TYPO3?

I'm using extbase in my extension and so I have *Repository classes where I can do simple queries just like:
public function getRecordsByCondition($config = [],$recordPages = null) {
$recordQuery = $this->createQuery();
$constraints = [];
if ($config['field1']) {
$constraints[] = $recordQuery->equals('field1',$config['field1']));
}
if ($config['field2']) {
$constraints[] = $recordQuery->equals('field2',$config['field2']));
}
if ($config['field3']) {
$constraints[] = $recordQuery->equals('field3',$config['field3']));
}
if (count($constraints)) {
if ($recordPages) {
$constraints[] = $recordQuery->in('pid',$recordPages);
$recordQuery->getQuerySettings()->setRespectStoragePage(false);
}
$recordQuery->matching($recordQuery->logicalAnd($constraints));
} else {
return false;
}
return $recordQuery->execute();
}
this will respect enableFields and other usual conditions.
on the other hand there is the option to do it in this way:
public function getrecords2($config,$recordPages) {
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('tx_myext_domain_model_records');
$rawquery = $queryBuilder
->select('*')
->from('tx_myext_domain_model_records')
->where(
$queryBuilder->expr()->eq('field1',$config['field1']),
$queryBuilder->expr()->eq('field2',$config['field2']),
$queryBuilder->expr()->eq('field3',$config['field3']),
$queryBuilder->expr()->in('pid', $recordPages),
$queryBuilder->expr()->eq('deleted',0),
$queryBuilder->expr()->eq('hidden',0)
// starttime, endtime, language, workspace, ....
);
return $rawquery->execute()->fetchAll();
}
where I need to care about enablefields by myself but have more options to specify the query.
On the first view you can see that there are other methods (eq vs. equals) and these kind of doing queries have no relation. But both work on the same table.
Now I'm at a point where I need to change all my work from first to second variant as I need a query with a join to another table which can't be done with first variant (as far as I know).
Have I missed something or does the first variant needs some enhancements?
Well, I am not sure exactly the difference but let me try to express things in brief as per my knowledge :D
The main difference between both queries is Individual database queries (Typically I call it Extbase query, I'm not sure I am right or not!) and another is Doctrine DBAL Queries
1. Individual database queries
Here, as per the modern approach extension use Domain modeling. So, TYPO3 already enables a secure connection for model (Typically database table) and you can use relational table connection with Extbase function (Select, operational, join etc..) provided by TYPO3 core.
For more: https://docs.typo3.org/m/typo3/book-extbasefluid/master/en-us/6-Persistence/3-implement-individual-database-queries.html
2. Doctrine DBAL
Here, you enable connection manually for the database table using ConnectionPool class. Also, you have more feasibility to establish a relation (or Join you can say!) according to your need.
For more: https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Database/Index.html
However, you can use restriction for taking care if hidden delete etc.
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('tx_myext_domain_model_records');
$queryBuilder->getRestrictions()->removeAll()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
$queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(HiddenRestriction::class));
$rawquery = $queryBuilder
->select('*')
->from('tx_myext_domain_model_records')
->where(
$queryBuilder->expr()->eq('field1',$config['field1']),
$queryBuilder->expr()->eq('field2',$config['field2']),
$queryBuilder->expr()->eq('field3',$config['field3']),
$queryBuilder->expr()->in('pid', $recordPages)
// starttime, endtime, language, workspace, ....
);
See: https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Database/RestrictionBuilder/Index.html
I know this is not a sufficient and 100% correct answer. Everyone can welcome to correct me :)
where I need to care about enablefields by myself
That's not true. By default there are Restrictions active and you can enable or disable every Restriction with a short command.
I use both approaches, but I use the first one only on Extbase extensions, the second one on every other extension. (Yes, there exist extensions without Extbase)

How do I implement, for instance, "group membership" many-to-many in Parse.com REST Cloud Code?

A user can create groups
A group had to have created by a user
A user can belong to multiple groups
A group can have multiple users
I have something like the following:
Parse.Cloud.afterSave('Group', function(request) {
var creator = request.user;
var group = request.object;
var wasGroupCreated = group.existed;
if(wasGroupCreated) {
var hasCreatedRelation = creator.relation('hasCreated');
hasCreatedRelation.add(group);
var isAMemberOfRelation = creator.relation('isMemberOf');
isAMemberOfRelation.add(group);
creator.save();
}
});
Now when I GET user/me with include=isMemberOf,hasCreated, it returns me the user object but with the following:
hasCreated: {
__type: "Relation"
className: "Group"
},
isMemberOf: {
__type: "Relation"
className: "Group"
}
I'd like to have the group objects included in say, 'hasCreated' and 'isMemberOf' arrays. How do I pull that using the REST API?
More in general though, am I approaching this the right way? Thoughts? Help is much appreciated!
First off, existed is a function that returns true or false (in your case the wasGroupCreated variable is always going to be a reference to the function and will tis always evaluate to true). It probably isn't going to return what you expect anyway if you were using it correctly.
I think what you want is the isNew() function, though I would test if this works in the Parse.Cloud.afterSave() method as I haven't tried it there.
As for the second part of your question, you seem to want to use your Relations like Arrays. If you used an array instead (and the size was small enough), then you could just include the Group objects in the query (add include parameter set to isMemberOf for example in your REST query).
If you do want to stick to Relations, realise that you'll need to read up more in the documentation. In particular you'll need to query the Group object using a where expression that has a $relatedTo pointer for the user. To query in this manner, you will probably need a members property on the Group that is a relation to Users.
Something like this in your REST query might work (replace the objectId with the right User of course):
where={"$relatedTo":{"object":{"__type":"Pointer","className":"_User","objectId":"8TOXdXf3tz"},"key":"members"}}

ASP.NET MVC FluentValidation with ViewModels and Business Logic Validation

I'm exploring using FluentValidation as it seems to be an elegant API for validation of my ViewModels upon model binding. I'm looking for opinions on how to properly centralize validation using this library as well as from my business (service) layer and raise it up to the view without having 2 different approaches to adding modelstate errors.
I'm open to using an entirely different API but essentially looking to solve this branching validation strategy.
[Side Note: One thing I tried was to move my business method into my FluentValidation's custom RsvpViewModelValidator class and using the .Must method but it seemed wrong to hide that call in there because if I needed to actually use my Customer object they I would have to re-query it again since its out of scope]
Sample Code:
[HttpPost]
public ActionResult AcceptInvitation(RsvpViewModel model)
{
//FluentValidation has happened on my RsvpViewModel already to check that
//RsvpCode is not null or whitespace
if(ModelState.IsValid)
{
//now I want to see if that code matches a customer in my database.
//returns null if not, Customer object if existing
customer = _customerService.GetByRsvpCode(model.RsvpCode);
if(customer == null)
{
//is there a better approach to this? I don't like that I'm
//splitting up the validation but struggling up to come up with a
//better way.
ModelState.AddModelError("RsvpCode",
string.Format("No customer was found for rsvp code {0}",
model.RsvpCode);
return View(model);
}
return this.RedirectToAction(c => c.CustomerDetail());
}
//FluentValidation failed so should just display message about RsvpCode
//being required
return View(model);
}
[HttpGet]
public ActionResult CustomerDetail()
{
//do work. implementation not important for this question.
}
To give some closure to the question (and make it acceptable) as well as summarize the comments:
Business/process logic and validation logic are two entities. Unless the validation ties in to the database (e.g. check for unique entries) there's no reason to group validation into one location. Some are responsible in the model making sure there's nothing invalid about the information, and some handle how the validated values are used within the system. Think of it in terms of property getters/setters vs the logic used in the methods with those properties.
That being said, separating out the processes (checks, error handling, etc.--anything not relating to UI) can be done in a service layer which also tends to keep the application DRY. Then the action(s) is/are only responsible for calling and presenting and not performing the actual unit of work. (also, if various actions in your application use similar logic, the checks are all in one location instead of throw together between actions. (did I remember to check that there's an entry in the customer table?))
Also, by breaking it down in to layers, you're keeping concerns modular and testable. (Accepting an RSVP isn't dependent on an action in the UI, but now it's a method in the service, which could be called by this UI or maybe a mobile application as well).
As far as bubbling errors up, I usually have a base exception that transverses each layer then I can extend it depending on purpose. You could just as easily use Enums, Booleans, out parameters, or simply a Boolean (the Rsvp either was or wasn't accepted). It just depends on how finite a response the user needs to correct the problem, or maybe change the work-flow so the error isn't a problem or something that the user need correct.
You can have the whole validation logic in fluent validation:
public class RsvpViewValidator : AbstractValidator<RsvpViewModel>
{
private readonly ICustomerService _customerService = new CustomerService();
public RsvpViewValidator()
{
RuleFor(x => x.RsvpCode)
.NotEmpty()
.Must(BeAssociatedWithCustomer)
.WithMessage("No customer was found for rsvp code {0}", x => x.RsvpCode)
}
private bool BeAssociatedWithCustomer(string rsvpCode)
{
var customer = _customerService.GetByRsvpCode(rsvpCode);
return (customer == null) ? false : true;
}
}

DBIx Class: overloading new() in a resultset

Hello dear community members.
I have a following problem. Say, I have a user table. During my programming I create a lot of search queries to this table. Then, later, I realize that I need to select always only "active" users, i.e. with "active" column set to TRUE. Now, instead of adjusting all my queries to the user table with additional filter (active => "true"), is it possible to overload new() in the resultset class or to do something that will globally change all my queries in the way I need?
Thanks a lot in advance.
Add a method to your User ResultSet class that returns a filtered resultset, for example:
sub search_active {
my $self = shift;
return $self->search({ active => 1 });
}
Also see the DBIx::Class docs on 'predefined searches' for more information.

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