Skip to content

Instantly share code, notes, and snippets.

@alanwillms
Created May 13, 2014 19:56
Show Gist options
  • Save alanwillms/b0cce14a22a49e2efdbc to your computer and use it in GitHub Desktop.
Save alanwillms/b0cce14a22a49e2efdbc to your computer and use it in GitHub Desktop.
Piores práticas
<?php
namespace app\models;
use yii\db\ActiveRecord;
use Mailer;
/**
* Adapted from:
* @see https://github.com/dpmccabe/rails-worst-practices/blob/master/user.rb
*/
class User extends ActiveRecord
{
const MAILCHIMP_API_KEY = 'm23lm092m3';
public function getOrders()
{
return $this->hasMany(Order::className(), ['user_id' => 'id']);
}
public function getPackages()
{
return $this->hasMany(Package::className(), ['id' => 'package_id'])
->viaTable('orders', ['user_id' => 'id']);
}
public function beforeSave($insert)
{
if ($insert) {
$this->assignReferralCode();
}
}
public function afterSave($insert)
{
if ($insert) {
$this->scheduleWelcomeEmail();
}
}
public function rules()
{
return [
[['email', 'fname', 'lname'], 'required'],
['referral_code', 'unique'],
];
}
public function getName()
{
return $this->fname . ' ' . $this->lname;
}
public function getFormattedName()
{
return '<strong>' . $this->name . "</strong> (<a href=\"mailto:{$this->email}\">{$this->email}</a>)";
}
public function assignReferralCode()
{
$this->referral_code = uniqid();
}
public function scheduleWelcomeEmail()
{
Mailer::delay()->welcome($this);
}
public function hasOrders()
{
return $this->getOrders()->count() > 0;
}
public function mostRecentPackageShippingAddress()
{
return $this->getOrders()->orderBy('created_at DESC')->one()->package->shipping_address;
}
public function canManage()
{
return in_array($this->email, ['manager@example.com', 'admin@example.com']);
}
public function orderProduct(Product $product)
{
$result = OrderProcessor::charge($this, $product);
if ($result) {
Event::logOrderProcessing($this);
Mailer::orderConfirmation($this, $product)->deliver();
return true;
} else {
Event::logFailedOrderProcessing($this);
return false;
}
}
public static function deleteUser($email)
{
try {
$user = User::find()->where(['email' => $email])->one();
$user.delete();
} catch (Exception $e) {
throw new Exception("Could not delete user with email {$email}");
}
}
}
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255) default(""), not null
# fname :string(255) default(""), not null
# lname :string(255) default(""), not null
# referral_code :string(255)
# created_at :datetime
# updated_at :datetime
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment