2021년 6월 28일 월요일
2021년 6월 21일 월요일
Top Laravel Eloquent Features You May Not Know.
1. Check if Model changed
You must keep look or identify if the model has been updated using isDirty()
$user = App\User::first();
$user->isDirty(); //false
$user->name = “Peter”;
$user->isDirty(); //true
If the individual attribute has been changed, you can also check.
$user->isDirty(‘name’); //true
$user->isDirty(‘age’); //false
2. Get original attributes
Once you develop the eloquent record and if you need original attributes, Just call getOriginal()
$user = App\User::first();
$user->name; //John
$user->name = “Peter”; //Peter
$user->getOriginal(‘name’); //John
$user->getOriginal(); //Original $user record
3. Get changed attributes
If you want to undo the changed attributes of a model, do it by using getChanges()
$user->getChanges()
//[
“name” => “Peter”,
]
Note: Here you need to keep in mind that, you will only get changes back if you save it or sync the changes with syncChanges()
4. Custom deleted_at column
In Laravel, the default deleted_at column is used for deleting, if you wish to change it, you need to define the DELETED_AT property.
class User extends Model
{
use SoftDeletes;
* The name of the “deleted at” column.
*
* @var string
*/
const DELETED_AT = ‘is_deleted’;
}
Or by defining an accessor.
class User extends Model
{
use SoftDeletes;
public function getDeletedAtColumn()
{
return ‘is_deleted’;
}
}
5. Save relationships and models
By using the push() method, you can save the relationships and models.
class User extends Model
{
public function phone()
{
return $this->hasOne(‘App\Phone’);
}
}
$user = User::first();
$user->name = “Peter”;
$user->phone->number = ‘1234567890’;
$user->push(); // This will update both user and phone record in DB
6. Reload fresh model
By using fresh(), you can Reload a fresh model
$user = App\User::first();
$user->name; // John
// user record get updated by another thread. eg: ‘name’ changed to // Peter.
$updatedUser = $user->fresh();
$updatedUser->name; // Peter
$user->name; // John
7. Reload existing model
By using the refresh(), we can reload existing models along with fresh value.
$user = App\User::first();
$user->name; // John
// user record get updated by another thread. eg: ‘name’ changed to // Peter.
$user->refresh();
$user->name; // Peter
8. Check if models are the same
You can identify if the models are same by using is()
$user = App\User::find(1);
$sameUser = App\User::find(1);
$diffUser = App\User::find(2);
$user->is($sameUser); // true
$user->is($diffUser); // false
9. Clone a model
With replicate(), you can clone a model. It helps you to create a copy and non-existing model instance.
$user = App\User::find(1);
$newUser = $user->replicate();
$newUser->save();
10. Specify attributes in find() method
Use find() or findOrFail() methods, to identify the attributes for selecting the second argument.
$user = App\User::find(1, [‘name’, ‘age’]);
$user = App\User::findOrFail(1, [‘name’, ‘age’]);
I wish it was interesting and helpful. You can show your love by sharing and commenting. Also, open to sharing the thoughts on this.
Finally…
If you want to utilize the best features of Laravel Eloquent for your Laravel based project. You can find out the best Laravel Development services and Hire Laravel Developer. Experienced and talented developers utilize the best resources and give you the best solution for development.
2021년 5월 6일 목요일
2021년 4월 15일 목요일
promise.all(), promise.any(), promise.race(), promise.allsettled() 차이 설명 쉬운 예제
2021년 4월 13일 화요일
SOLID Design Principles - 쉬운 설명
SOLID Design Principles — The Simplest Explanation.
If you working on small or even medium scale projects you may thoughts all these principles useless burden,
but for large-scale projects, you will definitely will realize the greatness of these principles.
Content:
Single Responsibility Principle (SRP)
Open-Closed Principle (OCP)
Liskov Substitution Principle (LSP)
Interface Segregation Principle (ISP)
Dependency Inversion Principle (DIP)
Single Responsibility Principle (SRP)
A class should have only one reason to change.
this means that a class should not be loaded with multiple responsibilities
and a single responsibility should not be spread across multiple classes or mixed with other responsibilities.
The reason is that the more changes requested in the future, the more changes the class needs to apply.
Example:
chief financial officer (CFO), chief operating officer (COO),
chief technology officer (CTO) responsible for Calculate payments, reports, and save data to the database respectively.
if we put all this logic into Employee class like that:
public class Employee {
public double CalculatePay(Money money) {
//logic for payments
}
public String reportHours(Employee employee) {
//logic for get report for employee
}
public Employee save(Employee employee) {
//store employee to the database
}
}
we will face a problem, and this problem is Employee class takes care of three different Responsibilities
(the logic of calculate payments, save Employee data to the database, and create reports).
we solve it by creating three different classes and make every class have Single Responsibility.
So what is the problem with putting all together?
if you work on a small project individually, you will see this, not a big deal to have all logic in one place, but in large scale projects,
there will a lot of cases for every method so for example calculatePay metho may depend on many methods based on the case
(each case have the different calculation), so the bigger project is the bigger logic needed, and in huge companies,
there is a team responsible for every part of project logic.
So in this example:
The calculatePay() method is specified by the accounting department, which reports to the CFO.
The reportHours() method is specified and used by the human resources department, which reports to the COO.
The save() method is specified by the database administrators, who report to the CTO.
For this reason, it not wise to put all logic in one place.
And this will be the new structure now all logic is separated from each other, and have employee data shared across them.
So now every team can work fine with their scope of the project without affecting other parts of the project.
But this leads to another problem which is developers now have three classes that they have to instantiate.
A common solution to this solve this problem is to use the Facade pattern.
Facade pattern
Facade pattern hides the complexities of the system and provides an interface to the client using which the client can access the system.
and after apply SRP the code will be something like that:
public class Employee {
// Employee Data
}
public class PayCalculator {
public double CalculatePay(Money money) {
//logic for payments
}
}
public class HourReport {
public String reportHours(Employee employee) {
//logic for get report for employee
}
}
public class EmployeeSaver {
public Employee saveEmployee(Employee employee) {
//store employee to database
}
}
Open-Closed Principle (OCP)
Software entities should be open for extension but closed for modification.
The OCP states that the behaviors of the system can be extended without having to modify its existing implementation.
New features should be implemented using the new code, but not by changing the existing code.
reduces the risk of breaking the existing implementation code.
if simple extensions to the requirements force massive changes to the software, then the architecture of that software is bad,
and a good software architecture would reduce the amount of changed code to the barest minimum. Ideally, zero.
build the classes in a way that we able to extend them by child classes and inheritance and once you created the class,
it no longer needs to be changed.
Example:
public enum paymentType = {Cash, CreditCard};
public class PaymentManager{
public PaymentType paymentType {get;set;}
public void Pay(Money money){
if(paymentType == PaymentType.cash){
// pay with cash
} else {
// pay with credit card
}
}
}
and if we need to add a new payment type? we need to modify this class.
open for extension:
public class payment{
public virtual void pay(Money money){
// base class
}
}
close for modification:
public class CashPayment:payment{
public override void pay(Money money){
// pay with cash
}
}
public class CreditCard:payment{
public override void pay(Money money){
// pay with credit card
}
}
Now if you need to add another payment logic you only need to create a new class and implement or extends the payment interface or base class.
If component A should be protected from changes in component B, then component B should depend on component A.
OCP USE-CASE
Liskov Substitution Principle (LSP)
A subclass should behave in such a way that it will not cause problems when used instead of the superclass.
LSP is a definition of a subtyping relation, called strong behavioral subtyping.
if S is a subtype of T, then objects of type T may be replaced with objects of type S without altering the desirable properties of the program.
Example:
Bad Example of LSP:
public class Bird{
public void fly(){}
}
public class Duck extends Bird{}
The duck can fly because it is a bird, But what about this:
public class Ostrich extends Bird{}
Ostrich is a bird, But it can’t fly, Ostrich class is a subtype of class Bird, But it can’t use the fly method,
that means that we are breaking the LSP principle.
Good Example of LSP:
public class Bird {
}
public class FlyingBirds extends Bird {
public void fly(){}
}
public class Duck extends FlyingBirds{}
public class Ostrich extends Bird{}
ability to replace any instance of a parent class with an instance of one of its child classes without negative side effect.
Interface Segregation Principle (ISP)
Developers shouldn’t be forced to depend upon interfaces that they don’t use.
Example:
public interface someInterface {
public int methodOne() {
// Do something
}
public int methodTwo() {
// Do somthing diffrent
}
}
if you want to implement this Interface
public someClass implements someInterface {
public int methodOne() {
// logic to do something
}
public int methodTwo() {
}
}
and only need to overwrite one method only why you forced to overwrite the other method and left it empty.
we solve this problem by creating two separate interfaces, every interface has only relevant methods.
public interface someInterface {
public int methodOne() {
// Do something
}
}
public interface someDiffrentInterface {
public int methodTwo() {
// Do somthing diffrent
}
}
Now you can implement the only interface you need.
depending on something that carries baggage that you don’t need can cause you troubles that you didn’t expect.
Dependency Inversion Principle (DIP)
High-level modules should not depend on low-level modules. Both should depend on abstractions.
Abstractions should not depend on details. Details should depend on abstractions.
components should depend on abstraction.
module need to manage high-level functionality with zero implementation details this allows the module to be used for any type of application
and for all modules inside the application.
Example:
we have an existing system which sends notifications to users by email
public class Email{public void sendMail(){// send mail
}
}public class Notification{private Email _email;public Notification(){_email = new Email();
}public void promotionalNotification(){_email.sendMail();
}
}
And if we need to send a notification by SMS, we need to change email to SMS in this class, which violates DIP, because the parent class doesn't depend on abstraction, it has a specific data tie to it.
we can solve it by:
1. create an interface.
public interface Messeneger{void sendMessage();
}
2. create classes implements this interface.
public class Email implements Messenger{
void sendMessage(){
// send email
}
}
public class SMS implements Messenaer{
void sendMessage(){
// send SMS
}
}
3. build class Notification which has Messenger property.
public class Notification{
private Messenger _messenger;
public Notification(){
_messenger = new Email();
}
public void promotionalNotification(){
_messeager.sendMessage();
}
}
You can replace crate a new object in three ways:
1. Constructor injection:
passing data to Notification Constructor
public class Notification{
private Messenger _messenger;
public Notification(Messenger messenger){
_messenger= messenger;
}
public void promotionalNotification(){
_messenger.sendMessage();
}
}
2. Property injection:
use the setter to set a Property of Notification class
public class Notification{
private Messenger messenger;
public void setMessenger(Messenger messenger) {
this.messenger= messenger;
}
public void promotionalNotification(){
_messenger.sendMessage();
}
}
3. Method injection:
pass object data to the method we want to use directly in Notification class
public class Notification{
public void promotionalNotification(Messenger messenger){
messenger.sendMessage();
}
}
2021년 4월 10일 토요일
10 Useful Python Snippets
1. Swap Two Variables With One Line of Code
Can you think of a way to swap two variables without the help of a third temporary variable? Well, here it is:
a = 1
b = 2
a, b = b, a
2. Duplicate Strings Without Looping
name = "Banana"
print(name * 4)
Output:
BananaBananaBananaBanana
3. Reverse a String
sentence = "This is just a test"
reversed = sentence[::-1]print(reversed)
Output:
tset a tsuj si sihT
4. Squash a List of Strings Into One String
words = ["This", "is", "a", "Test"]
combined = " ".join(words)print(combined)
Output:
This is a Test
5. Comparison Chains
In Python, you can combine comparisons neatly together instead of splitting the statement into two or more parts. For example:
x = 100
res = 0 < x < 1000
print(res)
Output:
True
6. Find the Most Frequent Element in a List
test = [6, 2, 2, 3, 4, 2, 2, 90, 2, 41]
most_frequent = max(set(test), key = test.count)
print(most_frequent)
Output:
2
7. Unpack List to Separate Variables
You can neatly unpack a list of elements to separate variables as long as the number of variables remains the same as the number of elements in the list.
For example:
arr = [1, 2, 3]
a,b,c = arrprint(a, b, c)
Output:
1 2 3
8. One-Liner If-Else Statements
In Python, one-liner if-else statements are known as ternary operators or conditional operators. For example:
age = 30
age_group = "Adult"
if age > 18
else "Child"print(age_group)
Output:
Adult
Generally, a conditional operator follows this pattern for your convenience:
true_expression if condition else false_expression
9. Loop Through a List With One Line of Code
You can use comprehensions to loop through a list with one line of code. For example, let’s raise each number in a list to the second power:
numbers = [1, 2, 3, 4, 5]
squared_numbers = [num * num for num in numbers]
print(squared_numbers)
Output:
[1, 4, 9, 16, 25]
Note: Comprehensions are not just limited to working with lists. You can use comprehensions in a similar one-liner fashion with dictionaries, sets, and generators as well.
Let’s see another example by using dictionary comprehension to raise the values of a dictionary to the second power:
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
squared_dict = {key: num * num for (key, num) in dict1.items()}
print(squared_dict)
Output:
{'a': 1, 'b': 4, 'c': 9, 'd': 16}
10. Simplify If Statements
Instead of this horrible mess:
if n == 0 or n == 1 or n == 2 or n == 3 or n == 4 or n == 5:
You can simply do this:
if n in [0, 1, 2, 3, 4, 5]
2021년 2월 15일 월요일
Linux Shell: fish
# zsh 보다 초기 설정도 간편하고 별도 설정없이 git, 자동제안 기능 등을 사용
# https://github.com/powerline/fonts 해당 폰트 중 일부가 필요할 수 있음
# 설치 방법
$ sudo apt-get install fish
Then install “Oh My Fish”:
$ curl -L https://get.oh-my.fish | fish
And set the theme to agnoster:
$ omf install agnoster
$ omf theme agnoster
~/.config/fish/config.fish 생성
사용하고자 하는 alias 작성
# Shorten things
alias ..='cd ..'
alias ...='cd ../../'
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'
alias c='clear'# If your terminal supports colors, use them!
alias ls='ls --color=auto'
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
alias diff='colordiff'# Works only if you have notify-send
# 설치 완료 후 shell 에서 fish 입력.